1、容器查询(Container Queries)
容器查询@container
类似于媒体查询@media
,区别在于查询所依据的对象不同。媒体查询依据的是浏览器的视窗大小,容器查询依据的是元素的父元素或者祖先元素的大小。
有关容器查询的属性一共有三个,分别是container-type
、container-name
、container
。
container-type
:标识一个作为被查询的容器,取值范围为size
、inline-size
、block-size
、style
、state
container-name
:被查询的容器的名字
container
:container-type
和container-name
的简写
使用方法
首先需要使用container-type
或者container
属性指定一个元素作为被查询的容器。然后使用@container
进行容器查询。
<template>
<div id="app">
<div>
<button @click="add" id="add">+</button>
<button @click="sub" id="sub">-</button>
</div>
<div class="demo">
<a>我的背景色会随着demo元素的宽度而变化</a>
</div>
</div>
</template>
<style>
.demo {
width: 200px;
height: 200px;
background: red;
container: inline-size;
}
@container (inline-size > 300px) {
a {
background: green;
}
}
</style>
当父元素的宽度为200px
的时候,背景色是红色的。