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

js设置css自定义变量_CSS变量(自定义属性)js 设置 css 自定义变量 Introduction 介绍 Thebasicsofu 使用变量的基础 Createvariab 在任何元素内创建变量 Variablessco 变量范围 Interactingw 使用 JavaScript 与 CSS 变量值进行交互 Hand

js设置css自定义变量

  • Introduction

    介绍

  • The basics of using variables

    使用变量的基础

  • Create variables inside any element

    在任何元素内创建变量

  • Variables scope

    变量范围

  • Interacting with a CSS Variable value using JavaScript

    使用JavaScript与CSS变量值进行交互

  • Handling invalid values

    处理无效值

  • Browser support

    浏览器支持

  • CSS Variables are case sensitive

    CSS变量区分大小写

  • Math in CSS Variables

    CSS变量中的数学

  • Media queries with CSS Variables

    使用CSS变量进行媒体查询

  • Setting a fallback value for var()

    为var()设置后备值

介绍 (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 ),然后是冒号和值。 像这样:

 
  1. :root {
  2. --primary-color: yellow;
  3. }

(more on :root later)

(稍后更多关于:root )

You can access the variable value using var():

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

 
  1. p {
  2. color: var(--primary-color)
  3. }

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

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

 
  1. :root {
  2. --default-padding: 30px 30px 20px 20px;
  3. --default-color: red;
  4. --default-background: #fff;
  5. }

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

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

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

 
  1. :root {
  2. --default-color: red;
  3. }
  4. body {
  5. --default-color: red;
  6. }
  7. main {
  8. --default-color: red;
  9. }
  10. p {
  11. --default-color: red;
  12. }
  13. span {
  14. --default-color: red;
  15. }
  16. a:hover {
  17. --default-color: red;
  18. }

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情况:

 
  1. :root {
  2. --primary-color: yellow;
  3. }

: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可用:

 
  1. .container {
  2. --secondary-color: yellow;
  3. }

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

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

Variables can be reassigned:

可以重新分配变量:

 
  1. :root {
  2. --primary-color: yellow;
  3. }
  4. .container {
  5. --primary-color: blue;
  6. }

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中分配或覆盖变量:

 


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设置变量值的方法如下:

 
  1. const element = document.getElementById('my-element')
  2. 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上定义的,则下面的代码可用于访问变量值:

 
  1. const styles = getComputedStyle(document.documentElement)
  2. 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:

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

 
  1. const element = document.getElementById('my-element')
  2. const styles = getComputedStyle(element)
  3. 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).

如果您需要支持较旧的浏览器,则可以使用PostCSS或Myth之类的库,但是由于将它们转换为旧的无变量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() ,例如:

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

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

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

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

 
  1. body {
  2. --width: 500px;
  3. }
  4. @media screen and (max-width: 1000px) and (min-width: 700px) {
  5. --width: 800px;
  6. }
  7. .container {
  8. width: var(--width);
  9. }

为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()接受第二个参数,这是未设置变量值时的默认后备值:

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

翻译自: CSS Variables (Custom Properties)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/227795.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月16日 下午8:31
下一篇 2026年3月16日 下午8:31


相关推荐

  • http请求生命周期流程

    http请求生命周期流程

    2021年10月30日
    40
  • directshow摄像头录像_open camera 使用方法

    directshow摄像头录像_open camera 使用方法Win1064+VS2012工程下载:http://download.csdn.net/detail/yulinxx/9263639建一个基于Dialog的MFC程序,而局如下:一个PIC控件,用于显示摄像头捕捉画面,几个按钮创建一个C++类,类名为:CCamera在CCamera.h中,需要包含#include#include”qedit.h”

    2022年10月12日
    5
  • GenAI Agents技术趋势:AI智能体技术的未来发展方向

    GenAI Agents技术趋势:AI智能体技术的未来发展方向

    2026年3月16日
    2
  • 频谱分析仪原理学习

    频谱分析仪原理学习 虽是电子专业出身,但在学生期间用频谱仪的次数比较少,连使用都不顺畅更加不会想到去研究它的原理。但现在的工作主要就是检测接收机,每天和频谱仪接收机各种设备打交道,有必要也很乐意的研究下各个设备的工作原理。讲解频谱仪原理的书籍有很多,读的第一本是师傅给我的安捷伦的《频谱分析原理》接着又自己看了《R&S的频谱分析原理》,相较于安捷伦R&S 更加注重从理论分析,个人…

    2022年8月11日
    10
  • c语言位运算符的用法_c语言运算符大全

    c语言位运算符的用法_c语言运算符大全一、位运算符C语言提供了六种位运算符:&按位与|按位或^按位异或~取反>>右移1.按位与运算按位与运算符”&”是双目运算符。其功能是参与运算的两数各对应的二进位相与。只有对应的两个二进位均为1时,结果位才为1,否则为0。参与运算的数

    2022年10月5日
    4
  • 二进制数的补码及运算(1)

    二进制数的补码及运算(1)本人研究不深,如有错误请不吝赐教!!1.正数的补码表示正数的补码=原码负数的补码={原码符号位不变}+{数值位按位取反后+1}or={原码符号位不变}+{数值位从右边数第一个1及其右边的0保持不变,左边安位取反}以十进制整数+97和-97为例:+97原码=0110_0001b+97补码=0110_0001b-97原码=

    2022年10月21日
    6

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号