Have you ever had to change the number of grid columns for different screen sizes in your CSS?
Maybe you've found yourself duplicating the same code and changing the values over and over again? Well, there's an easier way to handle this!
The solution is CSS variables. Variables in CSS are just like in any other language. They allow you to define a value once and use it throughout your CSS code. You can then easily modify the value in one place, and it will update all the elements that use it.
The syntax for CSS variables is simple. You define a variable using the --
prefix followed by a name and assign it a value. You can then use the variable by referencing its name with the var()
function.
Here's an example:
:root {
--primary-color: #007bff;
}
button {
background-color: var(--primary-color);
color: white;
}
In this example, we've defined a variable called --primary-color
with a value of #007bff
. We then use this variable to set the background color of all buttons on our page. If we later decide to change the primary color of our website, we can simply modify the --primary-color
variable in one place, and it will update all the buttons that use it.
Now, let's apply this concept to our pain point. Let's say we have a grid layout with two columns on small screens, but we want to change it to three columns on larger screens. We can use CSS variables to define the number of columns and update it for different screen sizes.
Consider this markup:
<div class="grid">
<div class="item">1</div>
<div class="item">2</div>
...
<div class="item">6</div>
</div>
Here’s the CSS:
:root {
--grid-columns: 2;
}
.grid {
display: grid;
grid-template-columns: repeat(var(--grid-columns), 1fr);
}
@media screen and (min-width: 768px) {
:root {
--grid-columns: 3;
}
}
In this example, we've defined a variable called --grid-columns
with a value of 2
for small screens. We then use a media query to update the value of --grid-columns
to 3
for larger screens. We use the repeat()
function to repeat the 1fr
value for the number of columns specified by the --grid-columns
variable.
With this approach, we can easily modify the number of grid columns for different screen sizes without having to duplicate the code or modify it for each individual element.
I hope this helps you save time in the future!
📘 I’m writing a new book!
If you loved this write-up and how it was explained, you’ll absolutely love my next eBook Level up with Tailwind CSS. Opened pre-orders last month and more than a hundred people have grabbed it already 🤯 Check it out!
📨 Newsletter suggestion
I love Tailwind CSS. If you love it too, I highly recommend subscribing to this one 👇
Tailwind Weekly: Weekly newsletter about all things Tailwind CSS. New issue every Saturday.
Thanks for the introduction to variables which was on my TODO list for a year ! Super simple concept I skipped learning about long ago.
This example is specific to grids but I see whole of other use-cases for myself.