How to define colors as variables in CSS ?
In CSS, we can define custom properties (often known as CSS variables), that offers us great flexibility to define a set of rules and avoid rewriting them again and again. We can also use custom properties to define colors.
Example 1:
<!DOCTYPE html> < html > < head > < title > How to define colors as variables in CSS? </ title > < style > :root { --primary-color: rgb(15, 157, 88); --secondary-color: rgb(255, 255, 255); } .first { width: 50%; padding: 40px 0px; margin: 10px 0px; text-align: center; /* Apply color using CSS var */ background-color: var(--primary-color); color: var(--secondary-color); } .second { width: 50%; padding: 40px 0px; text-align: center; /* Apply color using CSS var */ background-color: var(--primary-color); color: var(--secondary-color); } </ style > </ head > < body > < div class = "first" > < h1 >w3wiki</ h1 > </ div > < div class = "second" > < h1 >w3wiki</ h1 > </ div > </ body > </ html > |
Output:
Explanation: In the above example, we have defined two variable having scope of root (It can be used across the whole page), --primary-color
and --secondary-color
. Then, we have used them on class first and second, using CSS var() function.
Note: :root
selector can be replaced with any local selector. Also, it will limit the scope of the defined variable within that selector only.
Example 2:
<!DOCTYPE html> < html > < head > < title > How to define colors as variables in CSS? </ title > < style > .first { /* The defined colors are not scoped for .first class only */ --primary-color: rgb(15, 157, 88); --secondary-color: rgb(255, 255, 255); width: 50%; padding: 40px 0px; margin: 10px 0px; text-align: center; /* Apply color using CSS var */ background-color: var(--primary-color); color: var(--secondary-color); } .second { width: 50%; padding: 40px 0px; text-align: center; /* Apply color using CSS var */ background-color: var(--primary-color); color: var(--secondary-color); } </ style > </ head > < body > < div class = "first" > < h1 >w3wiki</ h1 > </ div > < div class = "second" > < h1 >w3wiki</ h1 > </ div > </ body > </ html > |
Output:
Contact Us