我想在现代Safari/Chrome浏览器中使用新的CSS容器查询.(Safari16.3,谷歌Chrome 113.0)

然而,基于高度的容器查询并没有像预期的那样工作.

预期结果:一旦外部容器变成蓝色(500px或更低的屏幕高度),我预计粉色正方形(500px容器的50vh)就会变成红色.

当前结果:正方形保持粉色,不会变成粉色.如果实现是宽度相对的,则该示例有效.

Did I do anything wrong in my implementation or is it just not jet implemented in Webkit engine? Any other solutions (without Javascript) to solve the problem, if in the final product the container will be resizeable by the user?

body {
    margin: 0
}

.container {
    height: 50vh;
    container-type: inline-size;
}

.test {
    width: 250px;
    height: 250px;
    background-color: hotpink;
}
            
@container (max-height: 250px) {
    .test {
        background-color: red;
    }
}
            
@media screen and (max-height: 500px) {
    .container {
        background: blue;
    }
}
<div class="container">
    <div class="test"></div>
</div>

推荐答案

inline-size个是宽度,而不是高度.你得用size

inline-size

查询将基于容器的内联尺寸.将布局、样式和内联大小包容应用于元素.ref

body {
    margin: 0
}

.container {
    height: 50vh;
    container-type: size;
}

.test {
    width: 250px;
    height: 250px;
    background-color: hotpink;
}
            
@container (max-height: 250px) {
    .test {
        background-color: red;
    }
}
            
@media screen and (max-height: 500px) {
    .container {
        background: blue;
    }
}
<div class="container">
    <div class="test"></div>
</div>

Css相关问答推荐

如何使用在另一个层定义块中定义的sass层作用域变量

如何解决 Spotify 嵌入代码中的白色背景错误?

如何取消 CSS 伪类中的属性设置?

如何在Bootstrap 5上使用移动设备居中内容?

如何在Safari中隐藏CSS的offset-path属性?CSS支持规则不按预期工作

为什么这个绝对定位的 ::after 伪元素会崩溃,除非父级有过滤器?

和号 (&) 作为 SASS @mixin 中的变量

CSS中元素的重叠

tailwind css 中的自定义组状态

如何禁用亚像素渲染或强制浏览器将属性舍入到最近的像素?

使用 CSS 在悬停时转换 SVG 路径的填充属性

你如何调试可打印的 CSS?

纯 CSS 滚动动画

使用 float:left 后如何获得新行?

如何在 CSS 中覆盖图像?

加载资源失败:服务器响应状态为 404(未找到)

如何使用 Gulp 复制多个文件并保持文件夹 struct

Angular 动画的目的是什么?

我应该使用最大设备宽度还是最大宽度?

是否可以在 CSS 中定义常量?