Web 功能:
容器查询(大小)
概览
借助感知大小的样式设置,组件可以根据其可用空间(而非整个屏幕的大小)来更改其布局或外观。这对于卡片或导航栏等组件非常有用,因为这些组件可能会放置在布局的不同部分(例如狭窄的边栏或宽阔的主区域)。
建议使用容器查询,因为这样可以使组件真正实现模块化。您无需知道组件将位于何处,也无需编写复杂的媒体查询来处理每种可能的布局。
实现
1. 定义容器
强制性:您必须先告知浏览器哪个元素是要衡量的容器。
.card-container {
/* Define the container type. Use 'inline-size' for width-based queries. */
/* You can also use 'size' for both width and height, but it requires explicit sizing. */
container-type: inline-size;
}
2. 根据容器大小应用样式
使用 @container 规则,在容器达到特定尺寸时应用样式。
/* Default styles for small containers (stacked layout) */
.card {
display: flex;
flex-direction: column;
gap: 1rem;
}
/* Styles for larger containers (side-by-side layout) */
/* This triggers when the container is wider than 400px */
@container (min-width: 400px) {
.card {
flex-direction: row;
align-items: center;
}
.card-image {
width: 150px;
height: 150px;
}
}
3. 有条件地显示内容
您还可以使用容器查询在有更多空间时隐藏或显示额外细节。
.card-details {
/* Hide extra details by default in small spaces */
display: none;
}
@container (min-width: 600px) {
.card-details {
/* Show details when there is plenty of room */
display: block;
}
}
后备策略
对于不支持容器查询的浏览器,最佳方法是使用安全的默认布局(例如堆叠式垂直布局),并在常规屏幕尺寸允许的情况下,使用媒体查询进行渐进增强。
/* Default safe stacked layout */
.card {
display: flex;
flex-direction: column;
}
/* Fallback using media queries for older browsers */
@media (min-width: 600px) {
.card {
flex-direction: row;
}
}
/* Overwrite with container queries where supported */
@supports (container-type: inline-size) {
@media (min-width: 600px) {
.card {
/* Reset media query fallback if needed, or let container query handle it */
flex-direction: column;
}
}
@container (min-width: 400px) {
.card {
flex-direction: row;
}
}
}
这可确保使用旧版浏览器的用户仍能获得可用的布局,即使该布局无法完美适应每个特定的容器宽度。