检测 @support
约 903 字大约 3 分钟
2025-04-12
在 Sass 中,@supports
是原生 CSS 的特性查询指令(Feature Queries),用于根据浏览器是否支持特定 CSS 属性或值来应用样式。Sass 完全兼容 CSS 的 @supports
语法,同时可以通过 Sass 的嵌套、变量、混合宏等特性提升代码可维护性。以下是详细用法和示例:
一、基础语法
@supports
的语法结构与原生 CSS 一致:
@supports (检测条件) {
/* 当条件满足时应用的样式 */
}
检测条件:
- 可以是属性检查(如
display: grid
、scroll-behavior: smooth
) - 特定的 CSS 函数(如
transform: translateX(calc(100% - 10px))
) - 特定伪类:
selector(:has(p))
- 逻辑组合(
and
/or
/not
)。
二、典型应用场景
1. 检测属性支持
// 检测浏览器是否支持 grid 布局
@supports (display: grid) {
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
}
2. 检测函数支持
// 检测是否支持 :has() 选择器
@supports selector(:has(p)) {
.parent:has(.child) {
border: 1px solid;
}
}
3. 逻辑组合条件
// 同时支持 Grid 和 Flexbox
@supports (display: grid) and (display: flex) {
.advanced-layout {
display: grid;
}
}
// 支持 Grid 或 Flexbox
@supports (display: grid) or (display: flex) {
.fallback-layout {
display: flex;
}
}
三、Sass 增强用法
1. 结合变量管理条件
通过变量统一管理检测条件:
$supports-grid: "(display: grid)";
$supports-subgrid: "(grid-template-columns: subgrid)";
@supports #{$supports-grid} and #{$supports-subgrid} {
.grid-system {
grid-template-columns: subgrid;
}
}
2. 嵌套使用
Sass 允许在规则内嵌套 @supports
:
.card {
padding: 20px;
@supports (backdrop-filter: blur(10px)) {
backdrop-filter: blur(10px);
background: rgba(255, 255, 255, 0.8);
}
}
编译结果:
.card {
padding: 20px;
}
@supports (backdrop-filter: blur(10px)) {
.card {
backdrop-filter: blur(10px);
background: rgba(255, 255, 255, 0.8);
}
}
3. 混合宏封装复用
创建可复用的特性检测混合宏:
@mixin supports-property($property, $value) {
@supports (#{$property}: #{$value}) {
@content;
}
}
// 使用
.box {
@include supports-property("aspect-ratio", "1/1") {
aspect-ratio: 1/1;
}
}
四、高级用法示例
1. 自动生成回退样式
结合 @supports not
为旧浏览器提供降级方案:
.hero {
// 现代浏览器:使用 aspect-ratio
@include supports-property("aspect-ratio", "16/9") {
aspect-ratio: 16/9;
}
// 旧浏览器:固定高度
@supports not (aspect-ratio: 16/9) {
height: 300px;
}
}
2. 检测自定义属性支持
:root {
--main-color: #3498db;
}
@supports (--css: variables) {
.theme-element {
color: var(--main-color);
}
}
3. 链式条件检测
@supports (scroll-behavior: smooth) and (overscroll-behavior: contain) {
html {
scroll-behavior: smooth;
overscroll-behavior: contain;
}
}
五、Sass 特有技巧
1. 动态生成条件
使用 Sass 函数生成复杂条件:
@function supports-flex-gap() {
@return "(gap: 1em) and (display: flex)";
}
@supports #{supports-flex-gap()} {
.flex-container {
gap: 1em;
}
}
2. 与媒体查询组合
嵌套 @supports
和 @media
实现响应式+特性检测:
@media (min-width: 768px) {
@supports (display: grid) {
.responsive-grid {
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
}
}
六、注意事项
浏览器兼容性
@supports
自身兼容性:所有现代浏览器均支持(IE 11 除外)。条件语法限制
检测的属性和值必须是浏览器可解析的,否则条件会被视为false
。性能影响
过度使用@supports
可能增加样式表解析时间,建议仅在必要时使用。与 CSS 原生变量结合
检测自定义属性支持时,需使用(--css: variables)
语法。
七、调试技巧
在开发过程中,可通过浏览器开发者工具直接查看 @supports
规则是否生效:
- 打开 Elements 面板
- 选中目标元素
- 在 Styles 选项卡中查看应用的规则和匹配的条件
八、总结
通过结合 Sass 的强大功能,@supports
可以更高效地管理浏览器兼容性代码,实现渐进增强的现代 Web 样式方案。核心原则是:优先为现代浏览器提供最优体验,同时为旧浏览器保留基础功能。
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于