CSS is awesome on its own but gets larger, more complex, and harder to maintain with time in large and complex projects. Sass or SCSS features like nesting, mixins, and inheritance helps in maintainable CSS for large projects.
Here is a quick glimpse of what Sass or SCSS looks like and how it can help:-
Variables
Create variables and produce styles dynamically by changing them, thus easing any changes in styles.
$font-stack: Helvetica, sans-serif;
$primary-color: #333;
body {
font: 100% $font-stack;
color: $primary-color;
}
Nesting
This is a faster and much better way to write styles for nested selectors.
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
}
li { display: inline-block; }
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}
Modules
We can break code into separate files, and then can use them by calling them using the @use keyword.
// _base.scss
$font-stack: Helvetica, sans-serif;
$primary-color: #333;
body {
font: 100% $font-stack;
color: $primary-color;
}
// styles.scss
@use 'base';
.inverse {
background-color: base.$primary-color;
color: white;
}
Mixins
These works like pre-made methods or functions that produce certain pre-defined styles.
@mixin theme($theme: DarkGray) {
background: $theme;
box-shadow: 0 0 1px rgba($theme, .25);
color: #fff;
}
.info {
@include theme;
}
.alert {
@include theme($theme: DarkRed);
}
.success {
@include theme($theme: DarkGreen);
}
Extend/Inheritance
This is just like a prototype or like a class in other languages, so that we can copy code from old template and then choose to overwrite certain parts according to new rules.
/* This CSS will print because %message-shared is extended. */
%message-shared {
border: 1px solid #ccc;
padding: 10px;
color: #333;
}
// This CSS won't print because %equal-heights is never extended.
%equal-heights {
display: flex;
flex-wrap: wrap;
}
.message {
@extend %message-shared;
}
.success {
@extend %message-shared;
border-color: green;
}
.error {
@extend %message-shared;
border-color: red;
}
.warning {
@extend %message-shared;
border-color: yellow;
}
Operators
With the help of operators we can use math functions to calculate values dynamically.
@use "sass:math";
.container {
display: flex;
}
article[role="main"] {
width: math.div(600px, 960px) * 100%;
}
aside[role="complementary"] {
width: math.div(300px, 960px) * 100%;
margin-left: auto;
}
I hope that was a quick revision for you 🙂