CSS variables - practical tips for working. Introduction to CSS Variables Variables and calc

Custom properties(sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values ​​to be reused throughout a document. They are set using custom property notation (e.g., --main-color: black;) and are accessed using the var() function (e.g., color: var(--main-color);).

Complex websites have very large amounts of CSS, often with a lot of repeated values. For example, the same color might be used in hundreds of different places, requiring global search and replace if that color needs to change. Custom properties allow a value to be stored in one place, then referenced in multiple other places. An additional benefit is semantic identifiers. For example, --main-text-color is easier to understand than #00ff00 , especially if this same color is also used in other contexts.

Custom properties are subject to the cascade and inherit their value from their parent.

Basic usage

Declaring a custom property:

Element ( --main-bg-color: brown; )

Using the custom property:

Element ( background-color: var(--main-bg-color); )

First steps with custom properties

Let's start with this simple CSS that applies the same color to elements of different classes:

One ( color: white; background-color: brown; margin: 10px; width: 50px; height: 50px; display: inline-block; ) .two ( color: white; background-color: black; margin: 10px; width: 150px; height: 70px; display: inline-block; .three ( color: white; background-color: brown; margin: 10px; width: 75px; ) .four ( color: white; background-color: brown; margin: 10px; width: 100px; .five ( background-color: brown; )

We"ll apply it to this HTML:

1:
2:Text 5 - more text

Which leads us to this:

Notice the repetition in the CSS. The background color is set to brown in several places. For some CSS declarations, it is possible to declare this higher in the cascade and let CSS inheritance solve this problem naturally. For non-trivial projects, this is not always possible. By declaring a custom property on the element and is identical to the selector html, except that its specificity is higher."> :root pseudo-class and using it where needed throughout the document, a CSS author can reduce the need for repetition:

:root ( --main-bg-color: brown; ) .one ( color: white; background-color: var(--main-bg-color); margin: 10px; width: 50px; height: 50px; display: inline-block; ) .two ( color: white; background-color: black; margin: 10px; width: 150px; height: 70px; display: inline-block; ) .three ( color: white; background-color: var( --main-bg-color); margin: 10px; width: 75px; .four ( color: white; background-color: var(--main-bg-color); margin: 10px; width: 100px; ) . five ( background-color: var(--main-bg-color); )

Text - more text

This leads to the same result as the previous example, yet allows for one canonical declaration of the desired property value.

Inheritance of custom properties

Custom properties do inherit. This means that if no value is set for a custom property on a given element, the value of its parent is used. Take this HTML:

With the following CSS:

Two ( --test: 10px; ) .three ( --test: 2em; )

In this case, the results of var(--test) are:

  • For the class="two" element: 10px
  • For the class="three" element: 2em
  • For the class="four" element: 10px (inherited from its parent)
  • For the class="one" element: invalid value, which is the default value of any custom property

Keep in mind that these are custom properties, not actual variables like you might find in other programming languages. The value is computed where it is needed, not stored for use in other rules. For instance, you cannot set a property for an element and expect to retrieve it in a sibling"s descendant"s rule. The property is only set for the matching selector and its descendants, like any normal CSS.

Custom property fallback values

Fallback values aren't used to fix the browser compatibility. If the browser doesn't support CSS custom Properties, the fallback value won't help. It"s just a backup for the browser which supports CSS Custom Properties to choose a different value if the given variable isn't defined or has an invalid value.

The first argument to the function is the name of the custom property to be substituted. The second argument to the function, if provided, is a fallback value, which is used as the substitution value when the referenced custom property is invalid. The function only accepts two parameters, assigning everything following the first comma as the second parameter. If that second parameter is invalid, such as if a comma-separated list is provided, the fallback will fail. For example:

Two ( color: var(--my-var, red); /* Red if --my-var is not defined */ ) .three ( background-color: var(--my-var, var(--my -background, pink)); /* pink if my-var and --my-background are not defined */ .three ( background-color: var(--my-var, --my-background, pink); /* Invalid: "--my-background, pink" */ )

Including a custom property as a fallback, as seen in the second example above, is the correct way to provide more than one fallback. The technique has been seen to cause performance issues as it takes more time to parse through the variables.

Note: The syntax of the fallback, like that of custom properties, allows commas. For example, var(--foo, red, blue) defines a fallback of red, blue - anything between the first comma and the end of the function is considered a fallback value.

Validity and values

The classical CSS concept of validity, tied to each property, is not very useful in regard to custom properties. When the values ​​of the custom properties are parsed, the browser doesn't know where they will be used, so must, therefore, consider nearly all values ​​as valid.

Unfortunately, these valid values ​​can be used, via the var() functional notation, in a context where they might not make sense. Properties and custom variables can lead to invalid CSS statements, leading to the new concept of valid at computed time.

What happens with invalid variables?

When the browser encounters an invalid var() substitution, the initial or inherited value of the property is used.

Consider the code snippet below.

HTML

This paragraph is initial black.

CSS

:root ( --text-color: 16px; ) p ( color: blue; ) p ( color: var(--text-color); )

As expected, the browser substitutes the value of --text-color in place of var(--text-color) , but 16px is not a valid property value for color . After substitution, the property doesn’t make any sense. The browser handles this situation in two steps:

  1. Check if the property color is inheritable. Yes, but

    Doesn't have any parent with color property. So move on to the next step.

  2. Set the value to its default initial value, i.e., black.

Result

The paragraph color will not be blue because invalid substitution is replaced by the initial value, not by the fallback. If you had written color: 16px without any variable substitutes, then it was a syntax error. The previous declaration will then be used.

Note: While a syntax error in a CSS property / value pair will lead to the line being ignored, using a cascaded value, invalid substitution -- using a custom property value that is invalid -- is not ignored, leading to the value to be inherited .

Values ​​in JavaScript

To use the values ​​of custom properties in JavaScript, it is just like standard properties.

// get variable from inline style element.style.getPropertyValue("--my-var"); // get variable from wherever getComputedStyle(element).getPropertyValue("--my-var"); // set variable on inline style element.style.setProperty("--my-var", jsVar + 4);

Those who have been involved in layout for a long time have felt many times that CSS code difficult to edit. For example, you wanted to change the color scheme on the entire page. What is needed for this? Change all blocks from one color to another. Uncomfortable? I agree, that's what they came up with SASS And LESS, however, this is a so-so solution. For example, you want to replace the entire color scheme through JavaScript, or increase the width of several blocks by 2 times? Obviously, this work requires writing monotonous code. Fortunately, relatively recently it became possible set variables directly in CSS, and browsers process them without problems. We will talk about this in this article.

Let's look at the following code:







Heading

Some text...


Basement




Declared in a pseudo element root(although you can declare variables directly in the elements themselves). Their use is very simple: instead of a specific property value, write var(variable_name). Particularly interesting is the use of variables together with a function calc(). Thanks to this, you can increase or decrease many elements on the site, while maintaining all proportions.

The only quality a language must have to qualify as a programming language is variables. They are considered incredibly useful, saving developers a lot of hours and effort. In addition, variables can improve the coding process in every way.

This is exactly what CSS not enough. Dinosaurs like Sass and Less used variables, but standard CSS never had variables. Up to this day.

They've been on the horizon for a long time, but it's only recently that variables have started to be implemented in CSS. So how do they work?

Browser support

Currently CSS variables are only supported Firefox Nightly. And in reality we cannot use them. However, despite the fact that they are still very, very raw (in beta testing), we are all looking forward to them appearing in our lives in the near future.

For browsers on the engine Webkit there is already a way to get the variables. In addition, they are also available for some versions Chrome, which are activated via flag in chrome://flags and using the -webkit- prefix.

As for IE, unfortunately we have to wait. Let's see what the upcoming release has in store for us.

How to Use CSS Variables

We all know very well how variables work, so only the syntax has undergone some changes. Here's how we'll declare variables in CSS:

Var-variable-name: value;

Global Variables

As in other programming languages, you can also set variables as global ones. For example, like this:

:root ( var-blue-color: #2980A6; var-text-color: #E0E0E0; )

I'm using the root pseudo element due to the fact that the top level interface in the DOM will be the one that holds these variables. And they, in turn, will work down the DOM tag tree for all our elements.

When it comes to using variables, we use the var() function to call a variable. This can be done like this:

Test ( background-color: var(blue-color); ) p ( color: var(text-color); )

Once we have declared a variable at the root of the document, we are now free to use it anywhere.

Context variables

In addition to global variables, you can set a variable to a specific element. In this case, its value will change:

One ( var-blue-color: #004F70; ) .one a ( color: var(blue-color); )

In this particular example, the anchor tags will inherit the new values ​​we set in their parent element. However, nothing outside of this div will use the values ​​set in the root element.

Conclusion

Variables CSS will be of great help when they stop looming on the horizon of the future and become reality. They may even be the first signal to abandon preprocessors and return to the standard CSS language.

  • Lesson prepared: website team

When working with CSS arguments, it can often be useful to think of them as two different types:

Primary custom properties

This is a property that you can change in different selectors, in media queries or using pseudo selectors:hover or:focus or with e.g. using JavaScript. Typically it contains one value:

: root ( --wrapper: 900px; --guter: 10px; )

Secondary Custom Properties

These are arguments that are calculated from others. For example, in the code below, the grid cell size (grid) --rowHeight is calculated from several primary ones. The result of the calculation is applied to the property, but is never updated manually - only recalculated as a result of changing the primary CSS variables.

It can be useful to prefix secondary arguments, as in this example, so that you and others working with your code know not to change them manually:

:root ( --wrapper: 900px; --guter: 10px; / * s-prefix denotes a secondary custom property * / --s-rh:calc((var(--wrapper)-(3*var(--guter )))/4); )

The only exception would be if you need to change how the value is calculated, but in theory it should be constant once it's set. This can discourage developers unfamiliar with your code from making changes unnecessarily.

Area of ​​visibility

In my examples I declare CSS variables in:root which represents the element :

:root ( ---bgColor: red; )

However, this is not strictly necessary, and moreover, this is not a good practice.

Most of the reasons why it is not recommended to set CSS variables in global scope in Javascript also apply to CSS. If you then wanted to use the custom background-color property -bgColor in different components, you would run into all the problems associated with scope. It's best to declare them in a selector, for example if you're working in components:

My-component ( ---bgColor: red; ) .some-other-component ( ---bgColor: blue; )

In the code snippet above, -bgColor is bound to each component, so you can use a variable with the same name without worrying about it affecting anything outside of that component.

Setting Default Values

With CSS variables you can set a default value (or multiple values). This means that in some situations you only need to declare your variables at the point at which they need to change. In the code below, the CSS variable -bgColor for the field is declared only when the width reaches 40em - before that it takes on the default value (red):

In this second example, you can see that the h1 and p selectors have different default values ​​for their color property, but both accept a variable on hover:

Using custom properties with preprocessor ones

One of the disadvantages of CSS arguments is that they do not work in media queries or pseudo classes, for example: nth-child(var(-n)) will not work. So most likely you will still want to use preprocessor arguments.

I would caution against mixing these two types of custom properties unless you fully understand their differences. Sass arguments are compiled before your code hits the browser, whereas in CSS they don't get a calculated value until they hit the browser. This means that in the code below, the width value for .box1 will work, but .box2 will throw an error because the value for -halfWidth is passed to the browser as a string:

$width: 600px; $halfWidth: $width/2; :root ( --halfWidth: $width/2; ) .box1 ( width: $halfWidth; ) .box2 ( width: var(--halfWidth); // this is incorrect )

However, you can use calc() as in the previous examples. See the result below:

If you inspect the element in the Chrome console and go to the Computed Styles tab, you will see that the width value for .box2 is not calculated. At our company we use a lot of Sass functions, for example to calculate rem from pixels when determining the size. I found that this turned out to be a problem when I tried to pass a Sass function into a CSS argument like --width: rem (600px) . There is a plugin PostCSS, which can convert pixels to rem to achieve the desired result, but I'll need to experiment with them a bit before I feel confident recommending them for use with CSS variables.

However, there are scenarios where using preprocessor and CSS variables in the same block of code together makes sense, such as in media queries as mentioned earlier.



2024 wisemotors.ru. How it works. Iron. Mining. Cryptocurrency.