本文共 2216 字,大约阅读时间需要 7 分钟。
备忘录吕吕没有备忘录十新建
CSS custom properties, also known as CSS variables, represent custom properties that can be declared and be called in your CSS.
CSS定制属性,也称为CSS变量,表示可以在CSS中声明和调用的定制属性。
To declare a Custom property in your CSS, you need to use the --
syntax:
要在CSS中声明Custom属性,您需要使用--
语法:
:root { --colorPrimary: hsla(360, 100%, 74%, 0.6); }
Notice the :root
pseudo-class selector — we can declare our variables globally using it. We can also declare them using other selectors, and they will then be scoped in those.
注意:root
伪类选择器-我们可以使用它全局地声明变量。 我们还可以使用其他选择器声明它们,然后将它们限定在这些选择器中。
.theme-dark { --colorPrimary: hsla(360, 100%, 24%, 0.6); }
To use a CSS custom property in your CSS, you can use the var()
function:
要在CSS中使用CSS自定义属性,可以使用var()
函数:
:root { --colorPrimary: tomato; } .theme-dark { --colorPrimary: lime; } body { background-color: var(--colorPrimary); }
In this case, body
will have a background colour of tomato
, but a body.theme-dark
of lime
.
在这种情况下, body
就会有一个背景颜色tomato
,但body.theme-dark
的lime
。
CSS custom properties can be declared without units if they are used with the calc()
function.
如果将CSS自定义属性与calc()
函数一起使用,则可以不使用单位声明它们。
:root { --spacing: 2; } .container { padding: var(--spacing) px; /*Doesn't Work 😫*/ padding: calc(var(--spacing) * 1rem); /*Will output 2rem 😃*/ }
To get a custom property, we can use the following:
要获取自定义属性,我们可以使用以下代码:
getComputedStyle(element).getPropertyValue("--my-var"); // Or if inline element.style.getPropertyValue("--my-var");
To update the custom property value:
要更新定制属性值:
element.style.setProperty("--my-var", newVal);
Example of getting and replacing values:
获取和替换值的示例:
In the following example, we use the to change the value of --scenePerspective, --cubeRotateY, and --cubeRotateX custom properties. This method makes it easier to apply a new style, as you do not have to apply inline style on each DOM element.
在以下示例中,我们使用来更改--scenePerspective,--cubeRotateY和--cubeRotateX自定义属性的值。 此方法使您更容易应用新样式,因为您不必在每个DOM元素上应用内联样式。
Thanks for reading!
谢谢阅读!
翻译自:
备忘录吕吕没有备忘录十新建
转载地址:http://epuzd.baihongyu.com/