注意目录和修改相同的字符编码

容器查询-----Container Queries

什么是 CSS 容器查询(Container Queries)?

在之前,对于同个样式,我们如果希望根据视口大小得到不一样效果,通常使用的是媒体查询

但是,一些容器或者组件的设计可能并不总是与视口的大小有关,而是与组件在布局中的放置位置有关。

所以在未来,新增了一种方式可以对不同状态下的容器样式进行控制,也就是容器查询。在最新的 Chrome Canary 中,我们可以通过 chrome://flags/#enable-container-queries 开启 Container Queries 功能。

假设我们有如下结构:

1 <div class="wrap">
2     <div class="g-container">
3         <div class="child">Title</div>
4         <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus vel eligendi, esse illum similique sint!!</p>
5     </div>
6 </div>

正常情况下的样式如下:

 1 .g-container {
 2     display: flex;
 3     flex-wrap: nowrap;
 4     border: 2px solid #ddd;
 5 
 6     .child {
 7         flex-shrink: 0;
 8         width: 200px;
 9         height: 100px;
10         background: deeppink;
11     }
12     
13     p {
14         height: 100px;
15         font-size: 16px;
16     }
17 }

在未来,我们可以通过 @container query 语法,设定父容器 .wrap 在不同宽度下的不同表现,在上述代码基础上,新增下述代码:

 1 .wrap {
 2     contain: layout inline-size;
 3     resize: horizontal;
 4     overflow: auto;
 5 }
 6 .g-container {
 7     display: flex;
 8     flex-wrap: nowrap;
 9     border: 2px solid #ddd;
10     .child {
11         flex-shrink: 0;
12         width: 200px;
13         height: 100px;
14         background: deeppink;
15     }
16     p {
17         height: 100px;
18         font-size: 16px;
19     }
20 }
21 // 当 .wrap 宽度小于等于 400px 时下述代码生效 
22 @container (max-width: 400px) {
23     .g-container {
24         flex-wrap: wrap;
25         flex-direction: column;
26     }
27     .g-container .child {
28         width: 100%;
29     }
30 }、
注意这里要开启 @container query,需要配合容器的 contain 属性,这里设置了 contain: layout inline-size,当 .wrap 宽度小于等于 400px 时,@container (max-width: 400px) 内的代码则生效,从横向布局 flex-wrap: nowrap 变换成了纵向换行布局 flex-wrap: wrap;
 
posted @ 2021-04-27 16:38  黑使  阅读(857)  评论(0编辑  收藏  举报