Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the CSS variable?

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the CSS variable". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the CSS variable".

Introduction to CSS variables

Today's browser development seems to replace popular libraries and extensions that currently provide us with functionality. ECMAScript 6 has almost no jQuery, and the next one in the crosshair seems to be CSS preprocessors, such as SASS and LESS. Modern versions of Firefox and Chrome support CSS variables (also known as CSS custom properties), which allow you to define variables directly in CSS, then reference them anywhere in the stylesheet, and even manipulate them using JavaScript. The result is a steroid CSS preprocessor, one that runs natively in the browser to boot. As IE Edge hopes to support this feature as soon as possible, these exciting moments are really a front-end developer.

Basic grammar

Using the CSS variable is a simple two-step process:

Use syntax to define the CSS variable-- myvariable-- in the selector. The selector determines the scope of the variable and its applicable location based on normal CSS inheritance and specificity rules. : root for example, the CSS variable defined within the selector can be used for all lower-level selectors (elements) in the document.

Use syntax to reference the CSS variable var (--myvariable) as an alternative to the static CSS attribute value.

Now let's look at a basic example of putting pedals on metal!

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

/ * Define CSS variables and scope * /

: root {

-- maincolor: black

-- secondarycolor: crimson

}

/ * Use CSS Variables * /

Body {

Background: var (--maincolor)

Color: white

}

Body p {

Background: var (--secondarycolor)

}

Here I define two CSS variables that contain the internal color values of the root selector. The selector that internally defines the variable sets its scope, and all descending selectors (elements) can access these variables. Defining CSS variables in the: root selector basically makes them available globally. At this point, the variable has not been applied anywhere, is dormant and ready to use. It is important to note that the CSS variable is not as sensitive as other CSS attributes, so-- maincolor and-- Maincolor are considered to be two different variables.

To use the CSS variable, we use the var () function to access its value by passing the variable name to it. Then, we select the desired CSS attribute to take advantage of the value of this variable.

You can even set all or part of the value of one CSS variable to another CSS variable:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

/ * Define CSS variables and scope * /

: root {

-- darkfont: brown

Darkborder: 5px dashed var (--darkfont)

}

/ * Use CSS Variables * /

Div.container {

Color: var (--darkfont)

Border: var (--darkborder)

}

Cascading and inheritance of CSS variables

The behavior of the CSS variable is very similar to that of other CSS properties in that their values are cascaded and inherited, unlike those defined using the CSS preprocessor. The following demonstrates cascading using the CSS variable:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

Root {

-- darkborder: 5px solid black

}

Body {

-- darkborder: 1px solid darkred

}

Img {

Border: var (--darkborder); / * img border will be 1px solid red * /

}

Here, I-- darkborder defines the same CSS variable twice in two different selectors. Because of the cascading rules, the rules within the BODY selector are more specific and win when used in the IMG element.

The CSS variable also inherits by default, so the value of the CSS attribute defined on the parent element penetrates down to the child element when used in these elements. We see this in the following example, where the UL boundary defined using the CSS variable on the UL element is also automatically applied to the child UL:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

: root {

-- myborder: 5px solid orange

}

Ul {

List-style: none

Padding: 10px

Margin: 0

Border-left: var (--myborder)

}

Ul ul {

Margin-left: 30px

}

Output screenshot:

Click screenshot to see live example

Disable inheritance

We can prevent the CSS variable from inheriting at some level by setting the CSS variable initial to a special value within the desired selector. Doing so resets the property to empty by default at the scope level. For example, to generally disable inheritance of CSS variables, we can do the following:

one

two

three

* {

-- somevar: initial; / * disable inheritance for-- somevar variable everywhere * /

}

Consider the next example, which disables variable inheritance at the myborder UL UL level, so variables applied at the UL level are not passed down to their descendants:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

: root {

-- myborder: 5px solid orange

}

Ul {

List-style: none

Padding: 10px

Margin: 0

Border-left: var (--myborder)

}

Ul ul {

-- myborder: initial; / * reset-- myborder variable * /

Margin-left: 30px

}

Output screenshot:

Click the screenshot to view a real-time example

Resetting the value of the CSS variable allows you to use a clean tablet where multiple CSS authors are working on the page, and there may be duplicate variable names and unexpected inheritance.

Use the calc () function to build a value

CSS variables can also be used with functions, so numeric values can be dynamic, making CSS variables closer to JavaScript variables: calc ()

one

two

three

four

five

six

seven

eight

nine

ten

eleven

: root {

-bottomgap: 30

}

H2 {

Margin-bottom: calc (var (--bottomgap) * 1px)

}

H3 {

Margin-bottom: calc (var (--bottomgap) * .5px) / * half of H1 gap * /

}

Here I set a CSS variable to a number, and then use the calc () function to derive the lower margins of the H1 and H2 elements, so that the latter is half of the previous element. Inside the calc () function, in order to derive the actual units (that is, pixels), we perform multiplication operations on the unit, such as-- bottomgap1px. Simply attaching a cell to the end of a variable will not work:

one

two

three

H2 {

Margin-bottom: calc (var (--bottomgap) px); / * doesn't work * /

}

You can also simply set-- bottomgap to the actual length at the beginning, such as 30px, and calculate half of the H2 element by dividing H2 by 2 (the right side of the division operation must always be a number). For more details on acceptable syntax, see this function. Calc ()

CSS variable and JavaScript

You can even use JavaScript to access and set CSS variables to simplify CSS-style operation by changing only the value of the CSS variable. Here are two JavaScript methods for getting and setting the value of the CSS variable, regardless of whether the attribute is defined directly on the element or inherited:

one

two

GetComputedStyle (element) .getPropertyValue ('--varname') / / get CSS variable value of an element, including any leading or trailing spaces

Element.style.setProperty ('- varname', 'newvalue') / / set CSS variable of an element to newvalue

To: root accesses the element / selector in JavaScript, use document.documentElement. When the value of the CSS variable changes, the browser automatically redraws to reflect the change. You can even set the value of one CSS variable to another CSS variable, creating interdependencies between CSS values, which have an interesting effect:

one

Element.style.setProperty ('- divheight', 'calc (var (--divwidth) / 2)') / / set one CSS property to the value of another

The following example creates a CSS bar clock that tells the current time by updating the CSS variable only with JavaScript. Each CSS variable enters the current hour, minute, or second as a percentage of the current 24 hours, 60 minutes, or 60 seconds, respectively. For example, 6: 00 p. M. will be converted to 6 to 24, or 25% of the hour field. We use these values to determine the number of background pseudo-elements to move (transform) in each bar. The results are as follows:

The only interaction between JavaScript and CSS is the CSS variable itself-the CSS variable opens up a new, arguably clearer way for JavaScript to manipulate CSS.

Set the CSS variable inline

The CSS variable can also be defined or set inline on an element so that you can adjust the value of the CSS variable for a single element. Suppose you have set two CSS variables in the stylesheet to define the rest and hover background colors for links within the UL. However, for specific links, you want the two colors to be different from the other colors. Overriding the default values of the two CSS variables in the link would be one way:

one

Home

Define the fallback value when the CSS variable is not defined

When using the CSS variable with the var (--cssvariable) function, you can populate the function with a second argument, which becomes a fallback value without defining a process variable. For example:

one

two

Background: var (--primarybg, white); / * Normal value as fallback value * /

Font-size: var (--defaultsize, var (--fallbacksize, 36px)); / * var () as fallback value * /

As you can see, the fallback value itself can be another CSS var () function, which can contain another fallback value without defining a variable.

The CSS variable fallback is obviously only available to browsers that support the CSS variable. To provide a backup value for browsers that do not support this feature, you can do the following:

one

two

Background: white; / * background value for browsers that don't support CSS variables * /

Background: var (--primarybg, white)

Thank you for your reading, the above is the content of "what is the CSS variable?" after the study of this article, I believe you have a deeper understanding of what the CSS variable is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report