Copy of Copy of 1. Newsletter visual (2).png

Dive into CSS Preprocessors

Published on 23 July 2019

Reading time 1 minute

We previously looked at how to fitting our code with SCSS, we are now going to look at a few tips that will make you save time in your development.

Let's imagine a code CSS as below:

    
.wrapper {
  background: #407FC7;
  color: #5D6063;
}
​
.header {
  background: #FFFFFF;
  color: #407FC7;
}
​
.footer {
  background: #5D6063;
}

We can observe several repetitive items, moreover, should I wish to change the color code of the website and the font, I would have to update a lot of lines in my code.

Now, let's transform this code in SCSS to understand the added value of variable here.


$primaryColor:#407FC7;
$secondaryColor:#5D6063;
$primaryFont:"Century";
​
.wrapper {
  background: $primaryColor;
  color: $secondaryColor;
  font-family: $primaryFont;
}
​
.header {
  background: $secondaryColor;
  color: $primaryColor;
  font-family: $primaryFont;
}
​
.footer {
  background: $secondaryColor;
  font-family: $primaryFont;
}

Now, by changing the values of my variables, I can easily update my whole graphic chart. I can already see you imagining huge files, and this is where happens the files import in SCSS.

Let's imagine that you wish to have a main file app.css with your whole code, but, for organizational reasons, you wish to break this file down into several smaller files while programming.

It is absolutely possible for you to do so with SCSS, in order to make this happen, you will only need to prefix the file using an underscore ( _ ). ​

You would have something like:

// _variables.scss

$primaryColor:#407FC7;
$secondaryColor:#5D6063;
$primaryFont:"Century";
​
// _footer.scss
​
.footer {
  background: $secondaryColor;
  font-family: $primaryFont;
}
​
// _header.scss
​
.header {
  background: $secondaryColor;
  color: $primaryColor;
  font-family: $primaryFont;
}

And you will then be able to recover everything inside your file app.scss: ​


@import "variables";
@import "header";
@import "footer";

SCSS really offer new possibilities and help us save so much time. 

Let's now imagine that we have a code like this:


.label-1 {
  padding-left: 10px;
}
​
.label-2 {
  padding-left: 20px;
}
​
.label-3 {
  padding-left: 30px;
}
​
.label-4 {
  padding-left: 40px;
}

With the @for loop, it is now possible to dynamically generate these different CSS classes:

@for $i from 1 through 4 {
  .label-#{$i} {
    padding-left: $i * 10;  }
}

With these new powers you will be able to code even faster and in a more efficient way. 

Have fun!