A blog about trying to make yourself better at making and designing websites. Also about random shit.

Tiny Web Wednesdays: How to organize your CSS with variables

Welcome to Tiny Web Wednesdays! It's where we talk a tiny bit about web development every Wednesday.

If you've ever written CSS before, you know that your code can get pretty unwieldy pretty quickly. Fortunately, variables can help you manage that complexity. So here are our options when it comes to using variables in CSS:

If you go to any website out there such as this, you'd see that there are many things that repeat throughout the page. Properties such as colors, font sizes, icon sizes, padding, and margins are all values that repeat throughout a webpage.

The solution to this problem of having to repeat values is to use variables! As we mentioned before, we have some options to choose from. Let's try out Sass:

See the Pen Colors in Sass by Jag Talon (@jagtalon) on CodePen.

Writing in Sass can make your CSS much more organized and easier to understand, but it's a language that your browser can't read. If you look at the example above, you'll see variables such as $yellow, $teal, and $blue. These are things that we can use throughout the code! Codepen processes this for us, and you can click on the button called "View Compiled" to see the CSS that's been made!

Sass not only gives us variables but other features as well such as the @each directive which makes our code extra sweet.

If you don't want to deal with any pre-processing and you want to use variables in your CSS, then you can use CSS Variables! Just be aware that not every browser supports this—that has to factor into your decision!

See the Pen Colors in CSS Variables by Jag Talon (@jagtalon) on CodePen.

CSS Variables are great when used in conjunction with media queries and JavaScript as well since they're dynamic! You can change them whenever you want.

See the Pen Text Demo by Jag Talon (@jagtalon) on CodePen.

Finally, know that you don't have to choose between one or the other—you can use both! In this talk, Lea Verou explains that the syntax of CSS Variables was chosen because people should be free to use them in conjunction with CSS pre-processors out there.

Nothing stopping you from using the awesome features of Sass such as @import and @mixin and @each to organize your code, while still being able to dynamically change CSS Variables from JavaScript.


If you liked this series, I'd love your support! You can get the episode early, get mentioned in the show, and show your love at Patreon! 🎉