什么是 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;