CSS Variables (aka custom properties)
What is a variable?
Before we begin, we should ask ourselves “What is a variable?”. Sounds familiar? Variables are used to store data (in memory) so that it can be referenced for later use.
name = "Daniel"Why use a variable?
It is useful for reducing repetition which is the essence of DRY (Don’t Repeat Yourself). Just like in any part of programming, CSS can get very long and messy very quickly. What if you couldn’t remember what value for a certain element? It can be difficult to maintain even for the simplest of things such as figuring out what the hex color of the“main-background-color”. Naming can often be overlooked but it is one of the most important property for a programmer. A good name can be one of the most difficult task to do.
Declaring a variable and assigning a value to it
You would use :root as the selector.
:root {
--main-bg-color: yellow;
--main-font-color: blue;
}Calling a variable
When calling a variable, you would use the var() function and the variable name as the argument within the parenthesis.
p {
color: var(--main-font-color);
}HMTL
<body>
<h1>Hello World</h1>
<div class='row1'>
<div class='box'>My Name is Daniel</div>
<div class='box'>I live in NYC</div>
<div class='box'>I love coding</div>
</div>
<div class='row2'>
<div class='box'>My Name is John</div>
<div class='box'>I live in Austin</div>
<div class='box'>I love BBQ</div>
</div>
<div class='row3'>
<div class='box'>My Name is Jane</div>
<div class='box'>I live in LA</div>
<div class='box'>I love biking</div>
</div>
</body>CSS
The beauty of CSS variables is that if you decide to change the value of multiple elements that shares the same value, you can only change it in one place instead of every selector. ‘row1’ and ‘row2’ share the same font color. If I decide to change it, I’d only have to change it in one place.
:root {
--row1-bg-color: #96ceb4;
--row2-bg-color: #ffeead;
--row3-bg-color: #ff6f69;
--primary-font-color: black;
--secondary-font-color: gray;
--box-font-color: white;
}h1 {
color: #ff6f69;
text-align: center;
}body {
font-family: "Trebuchet MS", Helvetica, sans-serif;
}:root {
--row1-bg-color: #96ceb4;
--row2-bg-color: #ffeead;
--row3-bg-color: #ff6f69;
--primary-font-color: black;
--secondary-font-color: white;
--third-font-color: gray;
}h1 {
color: #ff6f69;
text-align: center;
}body {
font-family: "Trebuchet MS", Helvetica, sans-serif;
}.box {
width: 25%;
height: 25%;
border: 1px solid gray;
display: inline-block;
text-align: center;
margin: 10px;
padding: 20px;
color: var(--primary-font-color);
}.row1, .row2, .row3{
text-align: center;
}.row1 .box {
background-color: var(--row1-bg-color);
color: var(--secondary-font-color);
}.row2 .box {
background-color: var(--row2-bg-color);
color: var(--third-font-color);
}.row3 .box {
background-color: var(--row3-bg-color);
color: var(--secondary-font-color);
}

