CSS @property 规则是 CSS Houdini API 的一部分,允许开发人员显式定义自定义属性。
@property 规则:
- 提供属性类型检查、约束、设置默认值和指定 CSS 自定义属性的继承行为等功能。
- 允许您在样式表中注册自定义属性,而无需使用 JavaScript。
- 创建已注册的自定义属性,类似于在 JavaScript 中使用等效参数调用 registerProperty()。
使用 CSS @property 规则时要记住几点:
- 有效的 @property 规则是指使用从规则 prelude 中的序列化派生的属性名称注册自定义属性。
- @property 规则必须同时包含 Syntax 和 inherits 描述符。如果缺少其中任何一个,则规则无效并将被忽略。
- 初始值 descriptor 仅对于通用语法定义是可选的,否则,它是必需的。如果缺少,则整个规则无效并忽略。
- @property 规则中的未知描述符将被忽略并被视为无效,但它们不会使整个 @property 规则失效。
语法
@property <custom-property-name> { <declaration-list> }
CSS @property - 使用自定义属性
以下示例演示了不使用 javascript 的 @property。
<html>
<head>
<style>
@property --main-color {
syntax: '<color>';
inital-value: black;
inherits: true;
}
.box {
--main-color: red;
background-color: var(--main-color);
width: 200px;
height: 200px;
margin: 50px auto;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 24px;
font-weight: bold;
text-align: center;
}
</style>
</head>
<body>
<div class="box">
<p>CSS At-Rules @property</p>
</div>
</body>
</html>
CSS @property - 使用自定义属性和 registerProperty()
以下示例演示了 @property 和 registerProperty() 的用法。
- 在以下示例中,CSS @property 定义了一个名为 --item-size 的自定义属性,并指定它接受并继承百分比值,并以初始值 40% 开头。
- JavaScript 中的 window.CSS.registerProperty 动态注册一个名为 --item-color 的新自定义属性,将其语法设置为 <color>,指定它不被继承,并为其分配一个初始值 peachpuff。
<html>
<head>
<style>
@property --item-size {
syntax: "<percentage>";
inherits: true;
initial-value: 40%;
}
/* set custom property values on parent */
.container {
display: flex;
height: 100px;
border: 3px dotted black;
--item-size: 50%;
--item-color: tomato;
--item-border: 5px solid green;
}
/* use custom properties to set item size and background color */
.item {
width: var(--item-size);
height: var(--item-size);
border: var(--item-border);
background-color: var(--item-color);
}
/* set custom property values on element itself */
.second {
--item-size: initial;
--item-color: inherit;
}
</style>
</head>
<body>
<div class="container">
<div class="item">First Item</div>
<div class="item">Second Item</div>
</div>
<script>
window.CSS.registerProperty({
name: "--item-color",
syntax: "<color>",
inherits: false,
initialValue: "peachpuff",
});
</script>
</body>
</html>
描述符
描述符 | 说明 |
---|---|
syntax | 解释属性允许的语法。 |
inherit | 确定默认情况下是否继承 @property 定义的自定义属性注册。 |
initial-value | 定义属性的初始值。 |