CSS Variables and how to use in stylesheet
Posted By : Priya verma | 31-May-2016
Css variable are know as custom variable.In other languages we use variables to store values the same concept we use in css. We use them to store the css properties and reuse by using css variable.
E.g.
CSS
h1 { color: #9c27b0; text-align:center; } h2 { text-align: left; } h3 { color: #9c27b0; text-align:center; } h4{ text-align:center; }
HTML
<h1>My First CSS Example</h1>
<h2>My First CSS Example</h2>
<h3>My First CSS Example</h3>
<h4>My First CSS Example</h4>
Note: In this example we use text-align property in many times by using css variable we define this property in one time and store in variable and use.
How to define css variable
To define custom property , add double-dash prefix with a custom property name
E.g
#div { --color: #9c27b0; or --default-color: #9c27b0; }
Generally we define custom property default value using :root pseudo selector. After define custom property in :root pseudo selector and we will use everywhere.
:root { --color: #9c27b0; --main-text-align:center; --main-bg-color: brown; }
And You also add another custom property and define in variable.
E.g
CSS
:root { --color: #9c27b0; --main-text-align:center; --main-bg-color: #ccc; } h1 { color: var(--color); text-align: var(--main-text-align); background-color: var(--main-bg-color); } h2 { text-align: left; } h3 { color: var(--color); text-align: var(--main-text-align); } h4{ text-align: var(--main-text-align); background-color: var(--main-bg-color); }
HTML
<body>
<h1>My First CSS Example</h1>
<h2>My First CSS Example</h2>
<h3>My First CSS Example</h3>
<h4>My First CSS Example</h4>
</body>
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Priya verma
Priya is a bright UI designer, having skills in , HTML, CSS, javascript, bootstrap. Her hobbies are playing outdoor games.