CSS @property:高级主题化
I’m happy to translate the article for you, but I’ll need the text you’d like translated. Could you please paste the content (or the portion you want translated) here? I’ll keep the source line exactly as you provided and preserve all formatting, markdown, and code blocks.
使用 @property 定义局部变量
@property --box-radius {
syntax: "*";
inherits: false;
initial-value: 16px;
}
@property --box-background {
syntax: "*";
inherits: false;
initial-value: #a2a3a3;
}
.box {
background: var(--box-background);
border-radius: var(--box-radius);
}
然后可以通过覆盖局部属性来应用变体:
.box-dark { --box-background: #626262; }
.box-light { --box-background: #d4d6d7; }
.box-rad-s { --box-radius: 8px; }
.box-rad-l { --box-radius: 32px; }
由于这些属性不继承,嵌套的盒子不会导致父级影响子级:
<div class="box">
Parent box with customized property values
<div class="box">
Child box with initial property values
</div>
</div>
将局部变量链接到全局值
为了避免硬编码值,在 :root 中定义全局变量,并将其作为回退值进行引用:
:root {
--global-background: light-dark(#dedede, #676767);
--global-radius: 16px;
}
/* 本地属性(不需要初始值) */
@property --box-radius {
syntax: "*";
inherits: false;
}
@property --box-background {
syntax: "*";
inherits: false;
}
/* 组件样式 */
.box {
background: var(--box-background, var(--global-background));
border-radius: var(--box-radius, var(--global-radius));
}
/* 主题变体 */
.box-dark { --box-background: oklch(from var(--global-background) calc(l - 0.2) c h / alpha); }
.box-light { --box-background: oklch(from var(--global-background) calc(l + 0.2) c h / alpha); }
.box-rad-s { --box-radius: calc(var(--global-radius) / 2); }
.box-rad-l { --box-radius: calc(var(--global-radius) * 2); }
现在,整个主题可以由少量全局变量驱动,而各个组件仍然保留各自的本地覆盖。
Source:
引入计算变量
当多个组件需要相似的转换时,引入一层 计算变量 会非常有用。这些变量充当全局 API 与局部实现之间的桥梁,使设计保持可预测性。
:root {
/* Global vars */
--global-background: light-dark(#dedede, #676767);
--global-radius: 16px;
/* Computed vars */
--radius-s: calc(0.5 * var(--global-radius));
--radius-m: var(--global-radius);
--radius-l: calc(2 * var(--global-radius));
--background-normal: var(--global-background);
--background-dark: oklch(from var(--global-background) calc(l - 0.2) c h / alpha);
--background-light: oklch(from var(--global-background) calc(l + 0.2) c h / alpha);
}
/* Local properties */
@property --box-radius {
syntax: "*";
inherits: false;
}
@property --box-background {
syntax: "*";
inherits: false;
}
/* Component styles */
.box {
--box-background: var(--background-normal);
--box-radius: var(--radius-m);
background: var(--box-background);
border-radius: var(--box-radius);
}
/* Theme variations */
.box-dark { --box-background: var(--background-dark); }
.box-light { --box-background: var(--background-light); }
.box-rad-s { --box-radius: var(--radius-s); }
.box-rad-l { --box-radius: var(--radius-l); }
通过这种结构,主题只公开少量高层变量(--global-background、--global-radius)。计算层定义了可接受的变体,而局部层则直接使用这些值,而不需要直接访问全局变量。这种分离保证了一致性,并使主题更易于扩展。
结论
使用三层 CSS 变量——global、computed 和 local——提供了一个干净、可预测的主题系统,符合开放‑封闭原则。未来的改进可以通过 @function at‑rule 暴露 computed 层,进一步保护内部值不被意外更改。
祝您前端开发愉快!