备忘录吕吕没有备忘录十新建_一份备忘单,可帮助您记住CSS自定义属性

备忘录吕吕没有备忘录十新建

CSS custom properties, also known as CSS variables, represent custom properties that can be declared and be called in your CSS.

CSS定制属性,也称为CSS变量,表示可以在CSS中声明和调用的定制属性。

在CSS中声明自定义属性 (Declare a custom property in 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); }

在CSS中使用自定义属性 (Use a custom property in CSS)

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-darklime

使用无单位的自定义属性 (Use custom properties without units)

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 😃*/ 
}

在JavaScript中使用自定义属性 (Use custom properties with JavaScript)

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 dat.gui controller library 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.

在以下示例中,我们使用dat.gui控制器库来更改--scenePerspective,--cubeRotateY和--cubeRotateX自定义属性的值。 此方法使您更容易应用新样式,因为您不必在每个DOM元素上应用内联样式。

Thanks for reading!

谢谢阅读!

翻译自: https://www.freecodecamp.org/news/css-customs-properties-cheatsheet-c86778541f7d/

备忘录吕吕没有备忘录十新建

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值