You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CSS能否检测浏览器支持Houdini CSS Properties and Values API的@property规则

纯CSS检测CSS Properties and Values API支持性的方案

问题背景

随着部分浏览器逐步引入CSS Houdini API,很多开发者会需要判断CSS Properties and Values API的支持情况。

已验证的可行JS检测方案

可以通过以下JS代码直接判断API是否存在:

typeof window.CSS.registerProperty !== 'undefined'

原生CSS检测的常见误区

很多开发者会首先尝试用@supports规则做检测,但当前CSS规范下的@supports仅支持校验普通CSS属性和值的合法性,不支持检测at规则的存在,因此以下写法无法正常生效:

@property --my-color {
  syntax: '<color>';
  inherits: false;
  initial-value: #c0ffee;
}

@supports ( @property : --my-color ) {
  body { background:DarkSeaGreen ; }
}

@supports not ( @property : --my-color ) {
  body { background:Crimson; }
}

纯CSS曲线检测方案

虽然没有直接的原生检测语法,但可以利用@property的特性做间接判断:通过@property定义的带类型约束的自定义属性,在接收到不符合语法规则的赋值时,会直接忽略该赋值、使用定义的初始值,而不会像普通自定义属性一样使用fallback值,利用这个差异就可以实现纯CSS侧的支持性检测:

/* 定义带颜色语法约束的测试用自定义属性 */
@property --support-flag {
  syntax: '<color>';
  inherits: false;
  initial-value: DarkSeaGreen; /* 支持@property时的标记色 */
}

body {
  /* 给自定义属性赋不符合color语法的值,同时设置fallback为不支持时的标记色 */
  --support-flag: invalid-value, Crimson;
  background: var(--support-flag);
}

上述代码运行后:

  • 如果浏览器支持CSS Properties and Values API,页面背景为深海绿色
  • 如果浏览器不支持该API,页面背景为深红色

内容的提问来源于stack exchange,提问作者Mark Notton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:18:02