CSS Variables and How To Use Them

A lot of people don’t know about CSS variables, and you might be one of them! It’s time to learn about CSS variables and how you can use them.

CSS variables are declared for a specific element as a custom property. Then, you can use that custom property anywhere you use that element.

Declaration and Usage

Here’s how you declare a custom property:

element { 
	--background-color: #f00;
}

Here, element can be a selector of any element, for example, div, p, .test, etc…

What we did is that we declared a custom property for this element called --background-color . All CSS custom properties must start with -- .

Inheritance

Elements can also inherit custom properties. For example, let’s say we have the following HTML:

<div class="parent">
	<div class="first-child"></div>  
    <div class="second-child"><div>
</div>

Then, we declare a variable called --text-size on .parent :

.parent {  
	--text-size: 15px;
}

Now, we can use --text-size not only inside .parent , but also inside its children as well:

.first-child {
    font-size: var(--text-size);
}

Fallback Values

You can also define a fallback value for a variable by passing a second parameter to var . For example:

.second-child {  
	font-size: var(--text-size, 30px);
}

#tips #css #design #css variables

CSS Variables and How To Use Them