Example of SASS Mixin, Variables, Partials, Inheritance & Nesting

Technology updates everyday. I am a UI developer, first time when I heard about SASS I started searching in Google to know “What is SASS?”. Off course I am an expert in CSS but how SASS is different from CSS? What are the advanced feature SASS provides compare to CSS? When CSS is here why SASS is introduced? Like plenty of queries I have at the Starting. Then I explore few advanced features of SASS such as SASS Mixin, SASS Variables, SASS Partials or SASS Nesting. In below sharing all those experiences with Example of SASS features.

Introduction to SASS

SASS (Syntactically Awesome Style Sheets) is a preprocessor scripting language that extends CSS, allowing developers to write styles in a more efficient and organized manner. It introduces features that are not available in standard CSS, making it a popular choice among web developers. While CSS3 offers numerous enhancements over its predecessors, SASS provides additional capabilities that streamline the styling process significantly.

The full name of SASS is “Syntactically Awesome Stylesheets“. It is a CSS extension language in run-time which is compiled into CSS. Large style sheets can easily maintain by SASS. SCSS is one of two syntax’s of SASS which uses block formatting like CSS. The extension for SASS file is .scss.

Steps to install SASS

To Getting Started with SASS, we need to install it first. Installer version of SASS is SASS gem. In Windows Operating System to run SASS we required Ruby at a min.

From Command line to install Sass gem run the following Command:

gem install sass

During installation if you found downloading issue, you can download the setup file manually from https://rubygems.org/gems/sass.

To run SASS from command line:

sass input.scss output.css

Sass can watch the changes in the Sass file and update the CSS using the following Command:

sass –watch input.scss:output.css

Advanced Features of SASS

Sass has introduced the following advanced features:

  • Nesting
  • Variables
  • Mixin
  • Inheritance
  • Partials

SASS Nesting

Nesting improves readability by visually representing the HTML structure, reducing redundancy, and making it easier to manage complex styles. However, over-nesting can lead to overly specific selectors, so it should be used judiciously.

In SASS we can able to nest selectors in the same hierarchy as of HTML.

Example of SASS Nesting:

SCSS code Output CSS
ul {
list-style: none;
li {
display: inline-block; 
a {
padding: 15px 20px;
}
}
}
ul {
list-style: none; }
ul li {
display: inline-block; }
ul li a {
padding: 15px 20px; }

SASS Variables

Variables in SASS allow developers to store reusable values such as colors, fonts, and spacing, making stylesheets more maintainable. In CSS, variables were introduced later (CSS Custom Properties), but SASS has supported them for much longer with broader browser compatibility.

SASS variables are compiled into static values, making them more predictable in older browsers. They also support mathematical operations and can be scoped within selectors, providing greater flexibility.

Using SASS it can possible to store any CSS values to variables. Variable name begins with a dollar($) sign and assignment uses a colon (:). We can do arithmetic operations to variables also.

Example of SASS Variables:

SCSS code Output CSS
/*Sass Variables*/
$font-normal: Arial, Verdana;
$primary-color: #DDDDDD;
/*Class*/
body {
font-family:  $font-normal;
background: $primary-color;
}
body {
font-family:  Arial, Verdana;
background: #DDDDDD; }

SASS Mixin

In SASS using Mixin technique we can define styles & the same styles can re-used throughout the stylesheet. To make more programmer friendly we can also pass arguments to Mixin.

Example of SASS Mixin:

SASS code Output CSS
@mixin border-radius($value) {
-webkit-border-radius: $value;
-moz-border-radius: $value;
-ms-border-radius: $value;
border-radius: $value; }

.button { 
@include border-radius(12px); 
}
.button {
-webkit-border-radius: 12px;
-moz-border-radius: 12px;
-ms-border-radius: 12px;
border-radius: 12px; }

SASS Inheritance

SASS inheritance, using `@extend`, allows selectors to inherit styles from another, promoting DRY (Don’t Repeat Yourself) principles. Unlike CSS, where inheritance is limited to native cascading, SASS enables explicit style sharing.

Using @extend selector in SASS we can inherit the styles from an another selector.

Example of SASS Inheritance:

SASS code Output CSS
.color-yellow {
color: #fc0;
}
.button {
@extend .color-yellow;
}
.color-yellow, .button {
color: #fc0; }

SASS Partials

To made modularization easy SASS introduced partial SASS files technique. A partial SASS file is named with a leading underscore, like _tempvariables.scss. This file is not converted to a CSS file. But we can import partial SASS files with the @import directive.

Example of SASS Partials:

@import "tempvariables";
@import "modules";

 

Enhanced Organization with Nesting

One of the primary advantages of SASS is its ability to nest styles. This feature allows developers to mirror the HTML structure in their CSS, making it easier to read and maintain. For example, instead of writing separate selectors for child elements, SASS enables nesting, which visually represents the hierarchy of elements. This reduces redundancy and clarifies the relationship between elements.

“`scss nav { ul { list-style: none; li { display: inline-block; a { text-decoration: none; } } } } “`

In the example above, the nested structure reflects the HTML layout, making it straightforward for developers to understand the context of each style.

Variables for Consistency

SASS introduces the concept of variables, which allows developers to store values such as colors, fonts, and sizes. This feature promotes consistency throughout a project and simplifies updates. For instance, if a brand color needs to change, developers can update the variable in one location, and the change will propagate throughout all related styles.

“`scss $primary-color: #3498db;

.button { background-color: $primary-color; color: white; } “`

Using variables not only enhances maintainability but also improves the overall efficiency of the development process.

Functions for Dynamic Calculations

SASS also provides the ability to create custom functions and use built-in functions for performing calculations. This feature allows for dynamic styling based on mathematical operations, facilitating more complex design requirements. For example, developers can easily calculate widths or margins based on existing values.

“`scss .container { width: 100%; padding: 20px; margin: 0 auto; @include border-radius(5px); }

.item { width: percentage(1 / 3); margin-right: 10px; } “`

The ability to perform calculations directly within stylesheets streamlines the process and reduces the need for additional JavaScript.

Control Directives and Expressions

SASS includes control directives like `@if`, `@for`, `@each`, and `@while`, which allow for conditional styling and looping through lists or maps. This capability is particularly useful for creating styles that adapt based on certain conditions or for generating repetitive styles dynamically.

“`scss $themes: (light, dark);

@each $theme in $themes { .theme-#{$theme} { background-color: if($theme == light, white, black); color: if($theme == light, black, white); } } “`

This level of control enables developers to write more dynamic and adaptable stylesheets.

Improved Maintainability and Scalability

As projects grow, maintaining CSS can become increasingly challenging. SASS addresses this concern by providing features that enhance maintainability and scalability. The use of variables, mixins, and modular partials allows teams to work more efficiently, making it easier to implement updates and new features without extensive rewrites.

Moreover, the organization provided by nesting and imports allows for a clearer structure, reducing the cognitive load on developers when navigating large codebases.

Compatibility with CSS3 Features

SASS is fully compatible with CSS3, meaning that developers can leverage all the modern features of CSS while benefiting from the enhancements that SASS offers. This compatibility ensures that teams can adopt SASS without sacrificing the advantages of newer CSS capabilities, such as flexbox, grid, and transitions.

Integration with Build Tools

SASS integrates seamlessly with popular build tools and task runners, such as Gulp, Grunt, and Webpack. This integration allows for automated compilation and minification of stylesheets, streamlining the development workflow. With these tools, developers can focus more on writing code and less on managing assets.

“`bash gulp.task(‘sass’, function() { return gulp.src(‘scss/*/.scss’) .pipe(sass().on(‘error’, sass.logError)) .pipe(gulp.dest(‘css’)); }); “`

By automating the compilation process, teams can ensure that their stylesheets are always up to date without manual intervention.

The advantages of using SASS over CSS3 are substantial, particularly in terms of organization, maintainability, and scalability. With features such as nesting, variables, mixins, and control directives, SASS provides developers with powerful tools to create efficient and dynamic stylesheets. As web projects continue to grow in complexity, adopting SASS can lead to cleaner code, easier maintenance, and a more streamlined development process. The integration with build tools and the support of a vibrant community further enhance its value, making SASS a compelling choice for modern web development.

Conclusion

SASS provides significant advantages over traditional CSS with features like nesting, variables, mixins, inheritance, and partials. These tools enhance code maintainability, reduce redundancy, and streamline development workflows. While CSS is essential for web styling, SASS’s advanced functionalities make it a powerful extension for modern developers. By leveraging these features, teams can write cleaner, more efficient, and scalable stylesheets.