js设置css自定义变量_CSS变量(自定义属性)

js设置css自定义变量

介绍 (Introduction)

In the last few years CSS preprocessors had a lot of success. It was very common for new projects to start with Less or SASS. And it’s still a very popular technology.

在过去的几年中,CSS预处理器取得了很大的成功。 对于新项目,通常以Less或SASS开始。 而且它仍然是一种非常流行的技术。

The main benefits of those technologies are, in my opinion:

我认为这些技术的主要优点是:

  • They allow to nest selectors

    它们允许嵌套选择器
  • The provide an easy imports functionality

    提供简单的导入功能
  • They give you variables

    他们给你变量

Modern CSS has a new powerful feature called CSS Custom Properties, also commonly known as CSS Variables.

现代CSS具有一个称为CSS自定义属性的新强大功能,通常也称为CSS变量

CSS is not a programming language like JavaScript, Python, PHP, Ruby or Go where variables are key to do something useful. CSS is very limited in what it can do, and it’s mainly a declarative syntax to tell browsers how they should display an HTML page.

CSS不是像JavaScript ,Python,PHP,Ruby或Go这样的编程语言,其中变量是执行有用操作的关键。 CSS的功能非常有限,它主要是一种声明性语法,用于告诉浏览器如何显示HTML页面。

But a variable is a variable: a name that refers to a value, and variables in CSS helps reduce repetition and inconsistencies in your CSS, by centralizing the values definition.

但是变量是变量:名称是指值,而CSS中的变量通过集中值的定义来帮助减少CSS中的重复和不一致。

And it introduces a unique feature that CSS preprocessors won’t never have: you can access and change the value of a CSS Variable programmatically using JavaScript.

并且它引入了CSS预处理器永远不会拥有的独特功能: 您可以使用JavaScript以编程方式访问和更改CSS变量的值

使用变量的基础 (The basics of using variables)

A CSS Variable is defined with a special syntax, prepending two dashes to a name (--variable-name), then a colon and a value. Like this:

CSS变量是使用特殊语法定义的,名称前两个破折号 ( --variable-name ),然后是冒号和值。 像这样:

:root {
  --primary-color: yellow;
}

(more on :root later)

(稍后更多关于:root )

You can access the variable value using var():

您可以使用var()访问变量值:

p {
  color: var(--primary-color)
}

The variable value can be any valid CSS value, for example:

变量值可以是任何有效CSS值,例如:

:root {
  --default-padding: 30px 30px 20px 20px;
  --default-color: red;
  --default-background: #fff;
}

在任何元素内创建变量 (Create variables inside any element)

CSS Variables can be defined inside any element. Some examples:

CSS变量可以在任何元素内定义。 一些例子:

:root {
  --default-color: red;
}

body {
  --default-color: red;
}

main {
  --default-color: red;
}

p {
  --default-color: red;
}

span {
  --default-color: red;
}

a:hover {
  --default-color: red;
}

What changes in those different examples is the scope.

这些不同示例的变化是范围

变量范围 (Variables scope)

Adding variables to a selector makes them available to all the children of it.

将变量添加到选择器使它们可用于所有选择器。

In the example above you saw the use of :root when defining a CSS variable:

在上面的示例中,您看到了在定义CSS变量时使用:root情况:

:root {
  --primary-color: yellow;
}

:root is a CSS pseudo-class that identifies the root element of a tree.

:root是CSS伪类,用于标识树的根元素。

In the context of an HTML document, using the :root selector points to the html element, except that :root has higher specificity (takes priority).

在HTML文档的上下文中,使用:root选择器指向html元素,除了:root具有更高的特异性 (优先级高)。

In the context of an SVG image, :root points to the svg tag.

在SVG映像的上下文中, :root指向svg标记。

Adding a CSS custom property to :root makes it available to all the elements in the page.

将CSS自定义属性添加到:root使其可用于页面中的所有元素。

If you add a variable inside a .container selector, it’s only going to be available to children of .container:

如果在.container选择器内添加变量,则仅对.container可用:

.container {
  --secondary-color: yellow;
}

and using it outside of this element is not going to work.

并且在此元素之外使用它将无法正常工作。

Variables can be reassigned:

可以重新分配变量:

:root {
  --primary-color: yellow;
}

.container {
  --primary-color: blue;
}

Outside .container, --primary-color will be yellow, but inside it will be blue.

.container外部,-- --primary-color将为黄色 ,但在其内部将为蓝色

You can also assign or overwrite a variable inside the HTML using inline styles:

您还可以使用内联样式在HTML中分配或覆盖变量:

<main style="--primary-color: orange;">
  <!-- ... -->
</main>

CSS Variables follow the normal CSS cascading rules, with precedence set according to specificity

CSS变量遵循正常的CSS级联规则 ,并根据具体情况设置优先级

使用JavaScript与CSS变量值进行交互 (Interacting with a CSS Variable value using JavaScript)

The coolest thing with CSS Variables is the ability to access and edit them using JavaScript.

CSS变量最酷的地方是可以使用JavaScript访问和编辑它们。

Here’s how you set a variable value using plain JavaScript:

使用纯JavaScript设置变量值的方法如下:

const element = document.getElementById('my-element')
element.style.setProperty('--variable-name', 'a-value')

This code below can be used to access a variable value instead, in case the variable is defined on :root:

如果变量是在:root上定义的,则下面的代码可用于访问变量值:

const styles = getComputedStyle(document.documentElement)
const value = String(styles.getPropertyValue('--variable-name')).trim()

Or, to get the style applied to a specific element, in case of variables set with a different scope:

或者,在变量设置为不同范围的情况下,将样式应用于特定元素:

const element = document.getElementById('my-element')
const styles = getComputedStyle(element)
const value = String(styles.getPropertyValue('--variable-name')).trim()

处理无效值 (Handling invalid values)

If a variable is assigned to a property which does not accept the variable value, it’s considered invalid.

如果将变量分配给不接受该变量值的属性,则认为该变量无效。

For example you might pass a pixel value to a position property, or a rem value to a color property.

例如,您可以将像素值传递给position属性,或者将rem值传递给color属性。

In this case the line is considered invalid and ignored.

在这种情况下,该行被视为无效并被忽略。

浏览器支持 (Browser support)

Browser support for CSS Variables is very good, according to Can I Use.

根据“我可以使用”的说法,浏览器对CSS变量的支持非常好

CSS Variables are here to stay, and you can use them today if you don’t need to support Internet Explorer and old versions of the other browsers.

CSS变量将保留下来,如果您不需要支持Internet Explorer和其他浏览器的旧版本,则可以在今天使用它们。

If you need to support older browsers you can use libraries like PostCSS or Myth, but you’ll lose the ability to interact with variables via JavaScript or the Browser Developer Tools, as they are transpiled to good old variable-less CSS (and as such, you lose most of the power of CSS Variables).

如果您需要支持较旧的浏览器,则可以使用PostCSSMyth之类的库,但是由于将它们转换为旧的无变量CSS(因此,)时,您将无法通过JavaScript或Browser Developer Tools与变量进行交互。 ,则会失去大多数CSS变量的功能)。

CSS变量区分大小写 (CSS Variables are case sensitive)

This variable:

此变量:

--width: 100px;

is different than:

不同于:

--Width: 100px;

CSS变量中的数学 (Math in CSS Variables)

To do math in CSS Variables, you need to use calc(), for example:

要在CSS变量中进行数学运算,您需要使用calc() ,例如:

:root {
  --default-left-padding: calc(10px * 2);
}

使用CSS变量进行媒体查询 (Media queries with CSS Variables)

Nothing special here. CSS Variables normally apply to media queries:

这里没什么特别的。 CSS变量通常适用于媒体查询:

body {
  --width: 500px;
}

@media screen and (max-width: 1000px) and (min-width: 700px) {
  --width: 800px;
}

.container {
  width: var(--width);
}

为var()设置后备值 (Setting a fallback value for var())

var() accepts a second parameter, which is the default fallback value when the variable value is not set:

var()接受第二个参数,这是未设置变量值时的默认后备值:

.container {
  margin: var(--default-margin, 30px);
}

翻译自: https://flaviocopes.com/css-variables/

js设置css自定义变量

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值