Information



Tags



Share

How to use CSS custom properties (Variables / :root)

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement



Definition

Sometimes, it is compelling to contemplate a theme design for your website so that you might want to change some variables such as main theme color or multiple element font types as you think about the theme. However, you have to find every variable you want to change or reuse in the stylesheet to redesign your theme. But, there is a simple way to achieve that – CSS custom properties(Variables). CSS custom properties should be declared within a CSS selector in order to define their scopes letting you access and reuse them properly. In that regard, you can reuse a CSS custom property more than once and change all of them by only changing the declared variable in the root selector. Do not forget you must declare a variable with two dashes(--) and use var() function to access the declared variable in CSS parameters as explained on the code below.

CSS custom properties Syntax(1)

CSS 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);).

CSS variables are subject to the cascade and inherit their value from their parent.

Code

Also, you can do much more by taking a further step with CSS custom variables; you can declare either whole CSS rules for elements or values for declarations by using them. As depicted below, you can declare a background image URL path and the font-size property within the root selector by using CSS custom properties.


:root{
--primary: white;
--secondary: #C5000C;
--font-size:25px;
--image: url('Spiderman.jpg');
--position: center;
--imageSize: cover;
--margin: auto;

}

.customProperties {position:relative;height:500px;width:80%;margin:var(--margin);background:var(--image);background-position: var(--position);background-repeat: no-repeat;background-size: var(--imageSize);}
.customProperties h2{position:absolute;bottom:0;right:0;color:var(--primary);font-size:var(--font-size);background-color:var(--secondary);text-align:right;}

Result:

By Todd Mcfarlane



References

(1) https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables