今天,CSS预处理器是Web开发的标准。 预处理器的一个主要优点是它们使您能够使用变量, 这有助于您避免复制和粘贴代码,并简化了开发和重构。
在本文中,您将了解到如何将CSS变量集成到CSS开发工作流程中,这会使得样式表更易于维护和不重复性。
现在,让我开始吧!
1* css变量的语法
<1> 什么是css变量?
如果您使用过任何一种编程语言,那么您应该已经熟悉了变量的概念。 变量允许您存储和更新程序所需的值以便工作。
在CSS中使用变量的好处与在编程语言中使用变量的好处并没有太大的不同。
以下是规范对此的说法:
[Using CSS variables] makes it easier to read large files, as seemingly-arbitrary values now have informative names, and makes editing such files much easier and less error-prone, as one only has to change the value once, in the custom property, and the change will propagate to all uses of that variable automatically.
W3C Specification .
[使用CSS变量]可以更容易地读取大文件,因为看似任意的值现在具有信息性名称,并且使得编辑此类文件更容易且更不容易出错,因为只需要在自定义属性中更改一次值 ,这种更改将自动传播到所有使用该变量的地方。
<2>css自定义变量语法
要声明变量而不是常用的CSS属性(如颜色或填充),只需提供以 - - 开头的自定义命名属性:
.box{ --box-color: #4d4e53; --box-padding: 0 10px;} |
属性的值可以是任何有效的CSS值:颜色,字符串,布局值,甚至是表达式。
以下是一些有用的自定义属性:
:root{ --main-color: #4d4e53; --main-bg: rgb(255, 255, 255); --logo-border-color: rebeccapurple; --header-height: 68px; --content-padding: 10px 20px; --base-line-height: 1.428571429; --transition-duration: .35s; --external-link: "external link"; --margin-top: calc(2vh + 20px); /* Valid CSS custom properties can be reused later in, say, JavaScript. */ --foo: if(x > 5) this.width = 10;} |
如果您不确定 :root,在HTML中它与html相同但具有更高的特异性,相当于全局变量。
<3> css变量的使用
var() 函数
您要通过 var() 这个 css 函数来使用 css 变量,将 css 变量名传入这个函数:
.box{ --box-color:#4d4e53; --box-padding: 0 10px; padding: var(--box-padding);}.box div{ color: var(--box-color);} |
var() 函数的语法是:
var( <custom-property-name> [, <declaration-value> ]? ) |
方法的第一个参数是要替换的自定义属性的名称。函数的可选第二个参数用作回退值。如果第一个参数引用的自定义属性无效,则该函数将使用第二个值。
新闻热点
疑难解答