CSS preprocessors are tools that help developers write CSS more efficiently by adding features that are not present in vanilla CSS. These features include variables, mixins, nesting, functions, and more. This lesson will examine three popular CSS preprocessors: Sass, Less, and Stylus.
Sass
Sass stands for “Syntactically Awesome Style Sheets.” It was initially released in 2006 and has become one of the most popular CSS preprocessors. Sass is available in two syntaxes: Sass (indented syntax) and SCSS (Sassy CSS).
Here’s an example of Sass code:
$primary-color: #007bff;
.navbar {
background-color: $primary-color;
a {
color: #fff;
&:hover {
color: darken($primary-color, 20%);
}
}
}
And here’s the same code in SCSS syntax:
$primary-color: #007bff;
.navbar {
background-color: $primary-color;
a {
color: #fff;
&:hover {
color: darken($primary-color, 20%);
}
}
}
Sass code can be compiled into regular CSS code using a Sass compiler. Many Sass compilers are available, including command-line tools and plugins for build tools like Grunt and Gulp.
Less
Less stands for “Leaner CSS.” It was created in 2009 and is similar to Sass in many ways. Less uses a syntax that is very similar to CSS, with a few added features.
Here’s an example of Less code:
@primary-color: #007bff;
.navbar {
background-color: @primary-color;
a {
color: #fff;
&:hover {
color: darken(@primary-color, 20%);
}
}
}
Like Sass, Less code can be compiled into regular CSS code using a Less compiler.
Stylus
Stylus is a relatively new CSS preprocessor that was released in 2010. Stylus has a syntax similar to Sass but is more flexible and customizable. Stylus also has a few unique features, such as optional semicolons and parentheses.
Here’s an example of Stylus code:
primary-color = #007bff
.navbar
background-color primary-color
a
color #fff
&:hover
color darken(primary-color, 20%)
Stylus code can be compiled into regular CSS code using a Stylus compiler.
Conclusion
CSS preprocessors can save developers time and effort by allowing them to write more efficient and reusable CSS code. Sass, Less, and Stylus are all great options, and choosing the right one depends on your personal preferences and the needs of your project.