CSS Variables - The var() Function

CSS Variables - The var() Function

One feature that was on?CSS wish lists?long before it became a standard is CSS Variables, officially referred to as CSS Custom Properties in the specification. CSS Variables have been a standard now for about a decade and all modern browsers have supported them for some time.

The?var()?function is used to insert the value of a CSS variable.

CSS variables have access to the DOM, which means that you can create variables with local or global scope, change the variables with JavaScript, and change the variables based on media queries.

A good way to use CSS variables is when it comes to the colors of your design. Instead of copy and paste the same colors over and over again, you can place them in variables.

CSS variables have access to the DOM, which means that you can create variables with local or global scope, change the variables with JavaScript, and change the variables based on media queries.

Syntax of the var() Function

The?var()?function is used to insert the value of a CSS variable.

The syntax of the?var()?function is declared thus;

var(--name, value)

To declare a variable in plain CSS, place two hyphens in front of the custom name you choose for the variable, or property, then use the?var()?function to place that value wherever you desire:

:root 
  --main: #030303;
  --accent: #5a5a5a;
}

.container {
  color: var(--main);
}

.footer {
  border-color: var(--main);
}

.sidebar {
  color: var(--accent);
}

.module {
  border-color: var(--accent);
}{        

In this example, I’ve defined two CSS variables:?--main?and?--accent. I’ve then used each CSS variable on two different elements, demonstrating the flexibility they open up. As with variables in any programming language, this allows you to declare a variable in a single place. If you later want to change that value everywhere in your stylesheet, it’s simply a matter of changing the original declaration and it will apply to all the places where you use the variable.

Note:?The variable name must begin with two dashes (--) and it is case sensitive!

How the var() function Works

  • First of all: CSS variables can have a global or local scope.
  • Global variables can be accessed/used throughout the entire document, while local variables can be used only inside the selector where it is declared.
  • To create a variable with global scope, declare it inside the: root?selector. The: root?selector matches the document's root element.
  • To create a variable with local scope, declare it inside the selector that is going to use it.

Where are CSS Variables defined?

As you can see in the example I provided above, you’ll often see CSS custom properties defined directly on the root element of an HTML document or shadow DOM. The :root?pseudo-class selector accomplishes this.

:root{ 
  --main: #030303;
  --accent: #5a5a5a;
}        

But CSS Variables aren’t limited to only being defined on the root element and it’s often beneficial to define them elsewhere. The?:root?selector is commonly chosen because this always targets the uppermost element in the DOM tree (whether it’s the full document or shadow DOM).

In most cases, you’d get the same result by defining custom properties on the?html?element (which is the root element in HTML documents) or even the?body?element. Using?:root?allows code to be more future-proof (e.g. if the spec one day add a new element as the root, the CSS would stay the same) and I suppose also allows for a stylesheet to apply to a different type of document that has a different root element.

Why “Custom Properties”?

In everyday conversation, developers often refer to this feature as “CSS variables”, in line with how preprocessors and programming languages refer to the same feature. But from a strictly technical perspective, these are not really “variables” but rather are?Custom Properties.

They have the same syntax as any predefined property in CSS, except for the two dashes that appear in front of the property name. The two dashes allow for CSS authors to use any valid?dashed identifier?without fear of conflict with regular CSS properties.

The spec explains that two dashes alone are invalid (apparently reserved for future use) and CSS will never give meaning to any valid dashed-identifier beyond its use as an author-defined custom property.

Unlike regular CSS properties, Custom Properties are case sensitive. This means?--main-color?is not the same as?--Main-Color. Valid characters to include in the custom property name are letters, numbers, underscores, and hyphens.

Advantages of using var()

  • makes the code easier to read (more understandable)
  • makes it much easier to change the color values

Technical notes about CSS Variables

In addition to being able to apply to any element, CSS Variables are fairly flexible and easy to deal with.

Here are some things worth noting:

  • They’re resolved with regular CSS inheritance and cascade rules
  • You can use them in media queries and other conditional rules
  • You can define them in an element’s?style?attribute
  • They can be?read or set?using features of the?CSS Object Model.

Tricks with CSS Variables

Several developers have shared tips and tricks using CSS Variables over the years. here’s a quick rundown of some coined from my research:

  • CSS Variables can be used in inline styles, as in the case of?aspect ratio boxes.
  • A space character is a valid value for a CSS variable, which allows you to do an on/off trick (e.g. for something like dark mode), which you can read about?in Lea’s post.
  • You can’t write hover styles in inline styles, but you can?get around this?using CSS Variables.
  • CSS Variables help to more easily create?multi-colored?SVGs,?as outlined here.
  • You can build practical and maintainable design systems and?themes?with CSS Variables, expounded on in detail?in this post
  • You can use CSS Variables to build more efficient and maintainable grids using?Grid Layout?features, as described?by Michelle Barker.

Conclusion

CSS Variables, or CSS Custom Properties, are ready to use today with well over 90% of globally in-use browsers supporting this handy feature. I hope this discussion of the basics and syntax will encourage you to consider CSS Variables in your newest projects if you haven’t done so already.

Casweeney Ojukwu

Rust | Cairo | Solidity | Yul - Assembly | Typescript - @codingcas

2 年

CSS has really evolved to what we used to do with it, now it has a lot of power compared to the days of just normal CSS when we use floats to layout a website. Now we have flex box, css grids, sass etc.

回复

要查看或添加评论,请登录

Solomon Iniodu的更多文章

  • Day 6/25: Mastering Application Security with Amazon Cognito

    Day 6/25: Mastering Application Security with Amazon Cognito

    Today was a deep dive into the world of cloud application security as I explored how to secure web applications using…

  • Bridging Gaps with Local Service Finder: Our Journey from Concept to Completion

    Bridging Gaps with Local Service Finder: Our Journey from Concept to Completion

    At the culmination of our 14-month Software Engineering Program with ALX Cohort 9, our team has proudly developed and…

  • Flyit

    Flyit

    Project Overview Traveling by air can be an exciting experience, but it can also be quite overwhelming. From booking…

  • Some PHP fun-facts

    Some PHP fun-facts

    Overview The term PHP is an acronym for Hypertext Preprocessor. PHP is a server-side scripting language designed…

  • Major Tools You Don't Want to Ignore as a Full Stack Developer in 2022

    Major Tools You Don't Want to Ignore as a Full Stack Developer in 2022

    There are a ton of full-stack developer tools. From IDEs to project management apps, you’ll find a plethora of options…

  • One trick you should know when working with the"typeof" operator in Javascript

    One trick you should know when working with the"typeof" operator in Javascript

    JavaScript has 5 different data types that can contain values: string number boolean object function The "typeof"…

  • Top 10 Popular Programming Languages And Their Creators

    Top 10 Popular Programming Languages And Their Creators

    Obviously, in the tech space today, we've come to terms with most programming languages. you know what they do, but do…

  • Basics of JavaScript

    Basics of JavaScript

    Overview JavaScript is a programming language that adds interactivity to your website. This happens in games, in the…

  • JavaScript Output

    JavaScript Output

    What is Javascript Output? JavaScript Output defines the ways to display the output of a given code. The process of…

  • JavaScript Tutorial Summary

    JavaScript Tutorial Summary

    This article is a summary of what I learned today (See the published date) about Javascript. The content here is…

社区洞察

其他会员也浏览了