Skip to main content

CSS Variables

CSS Variables, also known as CSS Custom Properties, 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);).

Setting CSS Variables

CSS variables are set on CSS selectors. They can be set on root, which makes them available globally, or they can be set on specific selectors, which makes them available within that specific selector.

:root {
--main-bg-color: coral;
}

In this example, --main-bg-color is the name of the variable and coral is its value. Now you can use this variable anywhere in your CSS by calling var(--main-bg-color).

Using CSS Variables

To use a CSS variable, you simply call the var() function and pass in the name of the variable.

body {
background-color: var(--main-bg-color);
}

In this example, the background color of the body will be coral, the value of --main-bg-color.

Scope of CSS Variables

CSS variables obey the rules of lexical scoping, which means the variable is available inside the element it's declared, as well as inside any of its child elements.

:root {
--main-color: blue;
}

#container {
--main-color: green;
}

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

If .box is a child of #container, its color will be green. If .box is not a child of #container, its color will be blue.

Fallback Value

The var() function can accept a second value which will be used as a fallback if the first variable is not set.

.box {
color: var(--non-existing, blue);
}

In this example, because --non-existing is not set, the color of .box will be blue.

Conclusion

CSS Variables are a powerful feature that can make your CSS more maintainable, readable, and reusable. They also provide a way to abstract certain CSS values, making your style sheets less repetitive and easier to understand.

Remember, variable names are case-sensitive and must start with two dashes. The var() function is used to insert the value of a CSS variable.

With CSS Variables, you now have the ability to create more dynamic styles and themes. Happy coding!