目录
- 支持多个属性
- 不支持某个特性时的样式
- 嵌套 @supports
- 性能考虑
- 兼容性
@supports
测试浏览器是否支持CSS功能,如果不支持则允许开发人员提供后备样式,这通常称为功能查询。
@supports (display: grid) {main {display: grid;}
}
在这个例子中,只有在浏览器支持 CSS Grid 布局的情况下,main 元素才会应用网格样式。
支持多个属性
@supports (display: flex) and (flex-direction: column) {.flex-column {display: flex;flex-direction: column;}
}
在这个例子中,只有在浏览器支持 Flexbox 布局及其 flex-direction 属性为 column 的情况下,.flex-column 类才会被应用。
不支持某个特性时的样式
您可以使用 not
来定义在不支持特定特性的情况下应用的样式。
@supports not (backdrop-filter: blur(5px)) {.overlay {background-color: rgba(0, 0, 0, 0.5);}
}
如果浏览器不支持 backdrop-filter 属性,.overlay 类将应用黑色半透明背景。
嵌套 @supports
可以在 @supports 块内嵌套其他条件:
@supports (display: grid) {@supports (grid-template-columns: repeat(3, 1fr)) {.container {display: grid;grid-template-columns: repeat(3, 1fr);}}
}
在这个例子中,只有在浏览器同时支持 grid 和 grid-template-columns 的情况下,才会应用相应的样式。
性能考虑
- 性能:尽量避免在 @supports 中使用复杂的条件,因为这可能会影响性能,尤其是在大型样式表中。
- 兼容性:@supports 在现代浏览器中得到广泛支持,但在某些老旧浏览器中可能无法使用。使用时请确保了解目标浏览器的支持情况。