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

兼容性

相关推荐
|晴 天|12 小时前
Vue 3 + TypeScript + Element Plus 博客系统开发总结与思考
前端·vue.js·typescript
猫32813 小时前
v-cloak
前端·javascript·vue.js
旷世奇才李先生13 小时前
Vue 3\+Vite\+Pinia实战:企业级前端项目架构设计
前端·javascript·vue.js
SoaringHeart15 小时前
Flutter进阶:用OverlayEntry 实现所有弹窗效果
前端·flutter
IT_陈寒17 小时前
Vite静态资源加载把我坑惨了
前端·人工智能·后端
herinspace17 小时前
管家婆实用贴-如何分离和附加数据库
开发语言·前端·javascript·数据库·语音识别
小码哥_常17 小时前
从MVC到MVI:一文吃透架构模式进化史
前端
嗷o嗷o17 小时前
Android BLE 的 notify 和 indicate 到底有什么区别
前端
豹哥学前端17 小时前
别再背“var 提升,let/const 不提升”了:揭开暂时性死区的真实面目
前端·面试
lar_slw18 小时前
k8s部署前端项目
前端·容器·kubernetes