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

兼容性

相关推荐
2分钟速写快排7 小时前
孔乙己的茴字有多少种写法?|AI 对话实时通信的三种实现
前端·javascript·github
Penge6669 小时前
JavaScript:BOM 详解
前端
Penge66610 小时前
Vite vs Webpack:前端构建工具原理与实战
前端
Penge66610 小时前
前端包管理工具:npm、Yarn、pnpm 快速入门
前端
Penge66610 小时前
Sass 了解
前端
Penge66611 小时前
Webpack 打包从 0 到 1 实战笔记
前端
Penge66611 小时前
Webpack 入门:是什么、为什么需要、怎么使用?
前端
Penge66611 小时前
Ant Design(Antd)了解
前端
wangruofeng11 小时前
同一行代码,百种渲染:Asuka、React Native 与 Flutter 跨平台渲染机制深度拆解
前端·github
Penge66612 小时前
JavaScript 核心语法速通
前端