How to use CSS Vars
permalinkCSS Vars are amazing, and you should leverage these where possible. I must admit I'm only using them recently, but a tip for any developer is if you have to reuse code, it's useless. Write better classes, have it in one stop etc.
CSS Vars can be a solution here, let's look at how these work.
HTML Setup permalink
<div class="section">
<div class="card card-blue"></div>
</div>
<div class="section">
<div class="card card-red"></div>
</div>
And then for the CSS we can do the following:
:root {
--primary-color: #89bbfe;
--secondary-color: #6f8ab7;
--card-color: #cae5ff;
--border-color: #acedff;
--border-radius: 10px;
--border-small: 3px;
--padding-medium: 10px;
--padding-small: 5px;
}
section {
width: 100vw;
height: 100vh;
background: var(--primary-color);
padding: var(--padding-medium);
display: flex;
justify-content: center;
align-items: center;
}
section:nth-child(even) {
background: var(--secondary-color);
}
.card {
width: 50%;
height: 50%;
background: var(--card-color);
padding: var(--padding-small);
border-radius: var(--border-radius);
border-top: var(--border-small) solid var(--border-color);
}
So the cool part is we declare the :root
section where we can make our variables this can be a lot of things including colours, paddings, spaces etc.
In our example you can see we can even use them inside complicated css statements like the border one: border-top: var(--border-small) solid var(--border-color);
. As you can see, we can use two variables without problems here.
Then in our code we use these variables like var({name})
you have to replace the {name} with the actual name.
You can see this in action in this Codepen.
See the Pen How to use CSS Vars by Chris Bongers (@rebelchris) on CodePen.
When to use CSS Variables? permalink
That's a good question, I think it's really important you don't re-use code it's quite useless to type the same code over and over so anything that is re-used you should make a variable for.
Also this process makes it way easier to change things in one place later on.
Let's say your boss wants to rebrand to red instead of blue, now you just have to change your variable and your done!
Browser support permalink
The bad thing about these awesome variables is that they are not supported by Internet Explorer.
Thank you for reading, and let's connect! permalink
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter