Tiny Web Wednesdays: How to organize your CSS with variables
Jag Talon Oct 17 Originally published at jagtalon.com on Oct 17, 2018
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:
- Using pre-processing tools such as Sass or Less or PostCSS.
- Using CSS custom properties AKA CSS Variables.
- Using both!
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:
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
$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!
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