【CSS/SCSS】@supports的介绍与用法

目录

@supports测试浏览器是否支持CSS功能,如果不支持则允许开发人员提供后备样式,这通常称为功能查询。

css 复制代码
@supports (display: grid) {
  main {
    display: grid;
  }
}

在这个例子中,只有在浏览器支持 CSS Grid 布局的情况下,main 元素才会应用网格样式。

支持多个属性

css 复制代码
@supports (display: flex) and (flex-direction: column) {
  .flex-column {
    display: flex;
    flex-direction: column;
  }
}

在这个例子中,只有在浏览器支持 Flexbox 布局及其 flex-direction 属性为 column 的情况下,.flex-column 类才会被应用。

不支持某个特性时的样式

您可以使用 not 来定义在不支持特定特性的情况下应用的样式。

css 复制代码
@supports not (backdrop-filter: blur(5px)) {
  .overlay {
    background-color: rgba(0, 0, 0, 0.5);
  }
}

如果浏览器不支持 backdrop-filter 属性,.overlay 类将应用黑色半透明背景。

嵌套 @supports

可以在 @supports 块内嵌套其他条件:

css 复制代码
@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 在现代浏览器中得到广泛支持,但在某些老旧浏览器中可能无法使用。使用时请确保了解目标浏览器的支持情况。

兼容性

相关推荐
JudithHuang1 小时前
Vue3 Vitest 单元测试进阶
前端·单元测试·log4j·vue
费曼学习法1 小时前
把 Agent 可观测性做进 Harness:从日志里只有 task finished 到全链路回放
前端
GuWenyue1 小时前
z-index 写到 9999 还是被盖住:把层叠上下文的 6 个反例全复现了一遍
前端·css·浏览器
htzyl2062 小时前
TypeScript:tsconfig配置误区及详情介绍,让你清清楚楚
前端·typescript
不服老的小黑哥2 小时前
0b · M2:服务化 + SSE 流式
前端
梦曦i2 小时前
0.9.0 新增页面级 style 支持
前端·uni-app x
不服老的小黑哥2 小时前
10a · M1:命令行 Agent
前端
疯华整猫2 小时前
类型全对、tsc 零错误,上线却白屏:AI 时代学 TypeScript,学的是它替不了的那一层
前端·typescript
Hilaku2 小时前
2027制药业4大ERP选型参考:主流厂商对比与优缺点分析
前端·javascript·程序员
不可能片场2 小时前
工程实践 管道截断让证据写不出来
前端·electron