CSS 变量
一句话解释
CSS 变量 (自定义属性) 是 reusable 值定义使用 --name and accessed 使用 var(), 启用 theming and DRY CSS.
用大白话说
CSS variables (officially "自定义属性") let you store values in a named variable and reuse them throughout your CSS. This makes it easy to maintain consistent design tokens (colors, spacing, fonts) and create themes.
You define a variable with a double dash: --主要-颜色: #2563eb; and use it with var(): 颜色: var(--主要-颜色);. Variables follow the cascade and can be overridden at any level — define global ones on :root and override locally on specific elements.
CSS variables are more powerful than preprocessor variables (Sass/Less) because they are dynamic — they can change at runtime with JavaScript, respect media queries, and cascade through the DOM. This makes them ideal for dark mode, theming, and responsive design.
示例
:root {
--primary: #2563eb;
--spacing: 1rem;
}
.button {
background: var(--primary);
padding: var(--spacing);
}
/* Dark mode override */
@media (prefers-color-scheme: dark) {
:root { --primary: #3b82f6; }
}CSS 变量 for theming, 使用 dark 模式 override using media 查询.
相关术语
相关资源
相关课程
- CSS 变量
学习 CSS 变量.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。