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

兼容性

相关推荐
Fairy要carry2 分钟前
项目01-手搓Agent之loop
前端·javascript·python
亲亲小宝宝鸭7 分钟前
Ctrl ACV工程师的提效之路:删掉项目中的冗余
前端
kyriewen10 分钟前
DOM树与节点操作:用JS给网页“动手术”
前端·javascript·面试
米饭同学i13 分钟前
基于腾讯云COS的小程序素材上传功能实现
前端·javascript·react.js
cxxcode13 分钟前
前端性能指标接入 Prometheus 技术方案
前端
辣椒炒代码14 分钟前
🚀 AI Agent 入门实战:基于 LangChain + MCP 构建智能导游助手
前端
ruanCat19 分钟前
前端工程化工具链从零配置:simple-git-hooks + lint-staged + commitlint
前端·git·代码规范
Jackson__42 分钟前
AI时代,前端开发者到底还剩下什么?又该往哪里走?
前端·ai编程
C澒1 小时前
微前端容器标准化:容器标准化演进
前端·架构
卖报的大地主1 小时前
Learn Claude Code Agent 开发 | 2、插拔式工具系统:扩展功能不修改核心循环
前端·chrome