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

兼容性

相关推荐
IMPYLH13 小时前
HTML 的 <html> 元素
前端·javascript·html
IT_陈寒13 小时前
SpringBoot自动配置的坑,把我整不会了
前端·人工智能·后端
赵大仁13 小时前
Human-in-the-loop:前端确认流与后端幂等
前端·后端·ai·agent·人机协作
恋猫de小郭13 小时前
超好用 R8 Configuration Analyzer, 优化你的 App 大小和内存
android·前端·flutter
赖龙1 天前
pnpm vs npm
前端·npm·node.js
学如逆水,不进则退1 天前
在线免费音频剪辑:NBTools 可视化波形裁剪 MP3/WAV,本地处理免上传
前端·音视频
Mh1 天前
虚拟滚动真的比普通滚动性能更好吗?
前端·javascript·性能优化
pe7er1 天前
React + Ant Design 中的 IME (输入法合成)安全输入组件
前端
Super 含1 天前
Android 启动优化(二):TTID、TTFD 与 Macrobenchmark 启动性能测量
前端
Python私教1 天前
别急着加 llms.txt:企业官网面向 AI 搜索的工程清单
前端·人工智能·seo