Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 17, 2021 06:57 pm GMT

CSS Variables: What Are They & How Can They Be Used?

When most web designers and developers hear the word "variable" with relevance to programming, they typically don't think of HTML or CSS first in their minds. When most non-web developers think of front-end languages, HTML and CSS for example, they see static, non-functional structural languages. For the most part, they're right! However, as with most programming, scripting, and even markup languages, there is more under the surface than first impressions would have you think.

What Are CSS Variables?

CSS variables, or "custom properties," operate much like most other variables in other programming languages. In comparison to Javascript, a language commonly seen operating next to CSS and HTML, CSS variables work very similarly, albeit with some limitations.

For example, CSS variables can be defined "globally" when included inside a :root or * selectors. Take the following code for example:

:root {  --red: #FF0000}

The attribute you see with the two dashes next to it, --red, is the CSS variable. With it, we assigned the color red as its value (#FF0000 in hexadecimal format.) Now that this variable is declared under the :root selector, it can be used anywhere in the rest of the stylesheet, as well as in any other stylesheets that include this one. That's because this variable is technically assigned to the root of the document, or the <html> tag.

The beauty of CSS variables is that we can assign more than just hex color values to them. According to the Mozilla Developer Network (MDN) page for CSS variables, you can assign color values, calc() values, pixel values, and much more! This is useful especially for specifying repeatedly-used colors like brand colors and setting breakpoint boundaries.

Now that we've learned how to set CSS variables, the next step is learning how to access them! To do this, all you need to use is the var() function.

Let's take a look back to the previous example using the --red variable. In order to use this variable to set the color of a paragraph element, for example, we can do this:

CSS:

:root {  --red: #FF0000}p {  color: var(--red)}

HTML:

<p>Hello world!</p>

Now, if we take a look at the final result, we should see this:

As you can see, our paragraph text is now a nice, clean red color! A good thing to keep in mind is that CSS variables always inherit their values from the parent first, then the child second if it is available. To demonstrate this, take a look at this new example, utilizing the previous example, but with a twist:

CSS:

:root {  --red: #FF0000}p {  --red: #00FF00;  color: var(--red)}

HTML:

<p>Hello world!</p>

...and now the final result:

Notice that our paragraph text is now green instead of red. How did this happen? We used the same variable, --red as before, so how come it isn't red anymore? Well, since we also defined a variable named --red in our p selector, it overwrote our previous definition of the red variable in the :root selector. This is something to keep in mind when defining and redefining CSS variables.

One more thing to keep track of is capitalization. In CSS variable names, capitalization is important. --red is not the same as --Red, for example. If you are finding that your CSS variable isn't working like you expected it to, the first thing I would check for is capitalization and spelling errors.

Real-world Applications

Now that we've covered the basics of CSS variables, let's take a look at some more real-world applications. Below is an example showing how you can resize elements using predefined breakpoint widths:

CSS:

:root {  --bp-wide: 500px;  --bp-narrow: 300px;}#container {  border: 2px solid #ff0000;  width: var(--bp-wide);}@media all and (max-width:520px) { /*Note that we can't use variables in media queries*/  #container {    width: var(--bp-narrow);    border-color: #0000ff;  }}

HTML:

<div id="container">  <p>Resize this page to see the breakpoint values in action!</p></div>

...and here is the final result.

Note that you will need to open this pen in a separate window and resize its width to see the result. If you don't want to do that, then I'll explain what happens.

In this example, the #container element has a default width of 500 pixels, set by the --bp-wide variable. However, in the later-defined media query in the CSS code, once the page width reaches 520 pixels, we change the container element's width by switching its value to the one defined in the --bp-narrow variable, which is 300 pixels (I also changed the border color from red to blue to better show the transition between the breakpoints.)

One limitation in using CSS variables as seen in this example is that we cannot use CSS variables in media queries. Instead, you must use static values.

One more real-world benefit of CSS variables is that they can be defined in external stylesheets and be imported to others to be used. The most common occurrence of this is storing all of the commonly-used site colors in one stylesheet, typically something called colors.css or global_colors.css, and importing it into another stylesheet like this:

@import url("colors.css");

By doing this, assuming that the variables are defined properly in the colors.css stylesheet, you can now use those variables in the new stylesheet as well!

One last feature of CSS variables, mainly the var() function, that I want to discuss are fallback values. By using the var() function, we can define a fallback value, or a value that is used if the main CSS variable that is defined is empty, invalid, or not applicable to its assignment parameter. Take the following example:

CSS:

p {    color: var(--foo, red)}

HTML:

<p>I'm a paragraph!</p>

Result:

You've probably noticed that the --foo variable has not been defined in our code yet! By using the fallback parameter in the var() function, we can define a default value in the case of an absent or undefined variable value. That's why the paragraph text in this example is red instead of the default black color. If we would've just used var(--foo) instead of var(--foo, red), the paragraph text would've remained black in this example instead of red. Note that black is not the ever-default color for all text. CSS will try to inherit a parent value before anything else. So if html has a color defined, the text will inherit that color first. Since, in this particular example, we don't have a predefined text color, the paragraph element will use our browser's default color, which is black.

Ending Remarks

As you probably assumed after reading this post, CSS variables are way more flexible and robust than I have covered here. The best way to feel the full potential of CSS variables is to start using them in your own code and read up more about them online!

As always, if you have any questions about CSS variables, please feel free to leave a comment or drop me an email! If you've enjoyed this tutorial, please feel free to leave a reaction and a comment showing your appreciation!


Original Link: https://dev.to/zfett/css-variables-what-are-they-how-can-they-be-used-4gj1

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To