SCSS - tutorial - the basics

Revision:


Content

SCSS - what it is! comments in SCSS nested selectors parent selector nested properties placeholders selectors script and expressions variables supported value types SCSS operators interpolation


SCSS - what it is!

top

SCSS (or, Sassy Cascading Style Sheet) is the superset of CSS or the more advanced version of CSS. Due to its advanced features it is often termed as "Sassy CSS".

SCSS is a "preprocessor" for CSS that provides additional highly useful features.
The syntax originally was derived from SASS which is a similar tool.
In addition to its useful features, SCSS has seen wide adoption because ".scss files" work with CSS styles.

The SCSS syntax uses the file extension ".scss". With a few small exceptions, it is a superset of CSS, which means essentially all valid CSS is valid SCSS as well.
Because of its similarity to CSS, it is the easiest syntax to get used to and the most popular.

SCSS looks like this:

        @mixin button-base() {
            @include typography(button);
            @include ripple-surface;
            @include ripple-radius-bounded;
          
            display: inline-flex;
            position: relative;
            height: $button-height;
            border: none;
            vertical-align: middle;
          
            &:hover { cursor: pointer; }
          
            &:disabled {
              color: $mdc-button-disabled-ink-color;
              cursor: default;
              pointer-events: none;
            }
        }
    

comments in SCSS

top

SCSS supports both single-line and multi-line comments i.e // and /* */. But once the SCSS file is compiled into CSS then the resulting CSS will only preserve the multiline comments, not the single-line comments, because CSS doesn't support single-line comments.

Block comments (/* */)in SCSS are included in the compiled CSS code, unless we compile in compressed mode. Additionally, if we add an exclamation mark to the start of a block comment (/*! */), it will always be included in the compiled CSS code even if we use compressed mode.

example 1: comments in SCSS

SCSS:
        // Hello
        // This is SCSS tutorial
        /*  This tutorial will help you to understand sass
            completely so that you can straight away apply sass
            in your project and make your project awesome.
        */

        // Thank you
        .hello-world{
            background-color:pink;
        }
    
CSS:
        /*  This tutorial will help you to understand sass
            completely so that you can straight away apply sass
            in your project and make your project awesome.
        */
        .hello-world {
            background-color:pink;
        }
    

example 1a: comments in SCSS

        // I am not included in the final compiled CSS code

        /* I am included in the final compiled CSS code unless
        * compressed mode is used */

        /*! I am always included in the final compiled CSS
        * code, even if compressed mode is used
        */
    

nested selectors

top

SCSS allows us to nest selectors that repeat the same root text. We can rewrite it for SCSS by using a nested selector.

Selectors can be placed inside the code block of other selectors and SCSS will automatically combine the outer rule’s selector with that of the inner rule.This means we don’t have to type the same selectors over and over again, saving on development time.

example 2: nested selectors

CSS:
        .header {
            width: 50%;
            margin: 0 auto;
        }
        .header-link {
            color: blue;
        }
    
SCSS:
        .header {
            width: 50%;
            margin: 0 auto;
          
            &-link {
              color: blue;
            }
        }  
    

SCSS is a preprocessor, meaning that it will read the second coding (i.e SCSS) and compile it into the first coding (i.e. CSS). The "& symbol" gets replaced with the name of the current selector. We can even nest selectors as deep as needed, though 3 levels is usually enough.

This technique is a big change from normal ".css selectors", however using nesting can greatly simplify the development process and volume of text on the screen.

example 3: nested selectors - code

        #sidebar {
            float:left;
            width:25%;
            background-color:lightblue;
            padding: 30px 10px;
            
            ul {
                list-style-type: none;
                margin: 0;
                padding: 0;
            }
            
            li {
                padding: 6px;
                margin-bottom: 10px;
                background-color: #10A2FF;
                color: #ffffff;
            }
        }
    

example 3a: nested selectors - code

        nav {
            background-color:#333;
            padding:1em;
            ul {
              margin:0;
              padding:0;
              list-style:none;
              li {
                display:inline-block;
              }
            }
        }
    

parent selector

top

In SCSS syntax, we can use the "& symbol" to represent the parent class and define further nested rules.

The & symbol gets compiled to the parent selector value when the SCSS code is transpiled to CSS code. This comes in handy when we have to use pseudo-selectors like ":hover", ":selected", etc. with the main element. So if you have an anchor tag and you want to define styling for it for mouse hover, you can do so like this in SCSS:

example 4: parent selector - &

        a {
            text-decoration: none;
            color:black;
            // using parent selector
            &:hover {
                color:red;
            }
        }
    

This is equivalent to the following CSS code:

        a{ 
            text-decoration: none;
            color:black;
        }
        a:hover
        {
            color:red;
        }
    

nested properties

top

Using nested properties, you can avoid rewriting CSS multiple times.

In CSS there are many properties that have the same prefix, such as "font-weight", "font-size", "font-family", etc. In CSS we have to type the complete property name to use them for styling HTML elements. But SCSS syntax allows us to define nested properties with the prefix declared only once like this:

example 5: nested properties

        font: {
            family: calibri;
            size: 12px;
            weight: 500;
        }
    

This is equivalent to the following CSS code:

        font-family: calibri;
        font-family: 12px;
        font-weight: 500;
    

placeholders selectors

top

Placeholder selectors or placeholder class in SCSS is used to define styling rules, which do not have any meaning by themselves, but provide meaning to the class which inherits this. SCSS supports "Inheritance".

We define a placeholder selector using the"%" symbol, provide some styling rules in it, and then we can inherit this class into other classes. This is very helpful when we have some common styling code that we want to include in multiple styling classes.

To work with placeholder selector, it has to be used with @extend directive. Without using @extend directive, you cannot display the result in CSS.

example 6: placeholder selectors

        %card {
            box-sizing: border-box;
            border-top: 1px rgba(#000, .12) solid;
            width: 100%;
        
            &:hover { border: 2px rgba(#000, .5) solid; }
        }
        
        .card-light {
            // inheriting card styling rules
            @extend %card; 
            background-color: #FFFFFF;
            color: #000000;
        }
        
        .card-dark {
            // inheriting card styling rules 
            @extend %card; 
            background-color: #000000;
            color: #FFFFFF;
        }
    

The above code will be transpiled into the following CSS code:

        .card-light, .card-dark {
            box-sizing: border-box;
            border-top: 1px rgba(#000, .12) solid;
            width: 100%;
        
        }
        
        .card-light:hover, .card-dark:hover {
            border: 2px rgba(#000, .5) solid;
        }
        
        .card-light {
            background-color: #FFFFFF;
            color: #000000;
        }
        
        .card-dark {
            background-color: #000000;
            color: #FFFFFF;
        }
    

script and expressions

top

SCSS supports writing simple script/expressions, which are evaluated when SCSS code is compiled into CSS code. Expressions are simple arithmetic operations that can be carried out using SCSS script or using built-in functions available in SCSS.

Simple expressions involving operations like addition, subtraction, multiplication, etc can be used in SCSS code.

example 7: expressions

        $text-size: 15px;
        #normal-text {
            font-size: $text-size;
        }
        #large-text {
            font-size: $text-size * 1.5;
        }
    

There are many functions available in SCSS by default, like the darken() function. These functions provide readymade ways to perform certain important actions in styling like darkening a color, lightening a color, creating Hexa code for a color using the rgb() function, etc.

example 8: functions

        $purple: #6A67CE;
        $darkpurple: darken($purple, 15%);
        .purple-btn{
            text-align: center;
            background-color: $purple;
        } 
        .purple-btn:hover{
            background-color: $darkpurple;
        }
    

variables

top

In .scss files we can set CSS values to variables like we would in strings JavaScript. The SCSS syntax for variables is: $variable-name: variable value

The variable declaration begins with "$", followed by the variable name, then a colon(:) symbol and finally the value for the variable.

example 9: variables

        $width-container: 1000px;
        $font-text: 'Noto Sans', 'Open Sans', sans-serif;
        $color-green: #29a634;
    

example 10: variables to define default values

        // define the variable
        $purple: #6A67CE;
        .purple-btn{
            text-align: center;
            background-color: $purple;
        }
        .purple-text{
            color: $purple;
        }
    

Variables in SCSS are defined outside of any selectors. We can call the variables above in our .scss styles like so:

example 11: variables

        .container {
            width: $width-container;
            font-family: $font-text;
            color: $color-green;
          }
    

The main benefit to using variables is that you can change every selector that uses them at once by adjusting their value. In CSS, those values are often scattered across multiple stylesheets and selectors so creating a seperate stylesheet for variables is helpful.

One more important point in defining and using variables in SCSS is that if you define a variable with the name having a "hyphen" or "underscore", these can be used interchangeably.

example 12: name with hyphen or underscore

        // define the variable
        $purple-color: #6A67CE; 
        .purple-btn { 
            text-align: center; 
            background-color: $purple-color; 
        } 
        .purple-text { 
            color: $purple_color;
        }
    

In the code above $purple-color and $purple_color will return the same value #6A67CE, so hyphen and underscore is treated as the same in variable name.

Just like other programming/scripting languages, variables in SCSS also have scope.

example 13: scope of SCSS variables

        // define the variable
        $purple: #6A67CE;
        .purple-btn { 
            text-align: center; 
            // re-defining the variable
            $purple: red;
            background-color: $purple; 
        } 
        .purple-text{ 
            color: $purple; 
        }
    

The above code will compile into the following CSS code:

        .purple-btn{
            text-align: center;
            background-color: red;
        }
        .purple-text{
            color: #6A67CE;
        }
    

You can use the !global switch to define a global variable from within a scope. But it is not recommended, because using the "!global switch" to define a global variable from within any selector will change the value of the variable for the entire stylesheet.

example 14: !global switch

        // define the variable
        $purple: #6A67CE;
        .purple-btn { 
            text-align: center; 
            // re-defining the variable
            $purple: red !global;
            background-color: $purple; 
        } 
        .purple-text { 
            color: $purple; 
        }
    

The above code will compile into the following CSS code:

        .purple-btn{
            text-align: center;
            background-color: red;
        }
        .purple-text{
            color: red;
        }
    

supported value types

top

The following are the value types supported in SCSS: numbers, strings, colors, Boolean values, null values, list of values, maps.

SCSS numbers are numerical values with or without a unit. SCSS supports all the units supported in CSS.

example 15: numbers

        @debug 100; /* 100 */
        @debug 0.8; /* 0.8 */
        @debug 16px; /* 16px */
    

SCSS automatically performs conversion for similar units while performing any operation on them. Also, if we multiply or divide two numbers of different units or the same units the operation is also performed on their units, so px * px becomes px square.

example 16: units

        @debug 4px * 6px; /* 24px*px (read "square pixels") */
        @debug 5px / 2s; /* 2.5px/s (read "pixels per second") */
    

When performing operation on compatible units, SCSS automatically coverts them, and for incompatible versions, SCSS will give an error.

example 17: operation on units

        /* CSS defines one inch as 96 pixels. */
        @debug 1in + 6px; /* 102px or 1.0625in */
        @debug 1in + 1s;
        /*     ^^^^^^^^
        * Error: Incompatible units s and in.
        */
    

SCSS strings are nothing but a sequence of characters. SCSS supports quoted strings, which is a sequence of characters enclosed within single or double quotes, and unquoted strings which are CSS identifiers, like bold, etc. To escape any string character we can use the "\" symbol.

example 18: strings

        @debug "Helvetica Neue"; /* "Helvetica Neue" */
        @debug bold; /* bold */
        @debug "\""; /* '"' */
        @debug \.widget; /* \.widget - dot symbol escaped */
    

There are many different ways for representing colors in the stylesheet in SCSS. SCSS colors can be written as hex codes (#f2ece4 or #b37399aa), CSS color names (midnightblue, transparent), or the functions rgb(), rgba(), hsl() and hsla().

example 19: colors

        @debug #f2ece4; /* #f2ece4 */
        @debug #b37399aa; /* rgba(179, 115, 153, 67%) */
        @debug midnightblue; /* #191970 */
        @debug rgb(204, 102, 153); /* #c69 */
        @debug rgba(107, 113, 127, 0.8); /* rgba(107, 113, 127, 0.8) */
        @debug hsl(228, 7%, 86%); /* #dadbdf */
        @debug hsla(20, 20%, 85%, 0.7); /* rgb(225, 215, 210, 0.7) */
    

SCSS Boolean are logical values "true" and "false". These are generally a result of using the equality or relational operators. SCSS Boolean values are useful while writing expressions to be used in @if and @else at-rules for controlling the flow control based on conditions.

example 20: Boolean values

        @debug 1px == 2px; /* false */
        @debug 1px == 1px; /* true */
        @debug 10px < 3px; /* false */
    

The value "null" is the only value of its type. It represents the absence of a value and is often returned by functions to indicate the lack of a result.

example 21: null

        @debug &; /* null */
    

SCSS supports "List" and also provides at-rule for iterating over these lists, like @for, @each, and @while at-rules. Values stored inside a list should be separated by commas or spaces as long as they are consistent. You can define lists by enclosing values between square brackets or even without brackets.

A SCSS List can have zero value, one value or more than one value. Also, Lists in SCSS are immutable, which means once defined they never change values, every time you change any value, a new list gets created.

While defining "mixins" or "functions" you can define Lists are arguments.

example 22: Lists

        $listvar: 1, 2, 3;
        /* using square barackets */
        $sides: ["left", "right", "top", "bottom"];
    

SCSS maps hold key-value pairs, where value can be accessed using the keys. Following is the syntax to create a map in CSSS: (<expression>: <expression>, <expression>: <expression>)

The expression which is before the ":" is the key, and the expression after is the value associated with that key. The keys must be unique, but the values may be duplicated. Also, to define a map parentheses () are required. To define an empty map, we use ().SCSS Maps are also immutable.

example 23: maps

        $font-weights: ("regular": 400, "medium": 500, "bold": 700);
    

SCSS operators

top

The simple rule of "BODMAS" (i,e, Bracket, Order, Division, Multiplication, Addition, and Subtraction) is being followed in case of mathematical operators in an expression.

We can also use parentheses to structure any expression while using operators in SCSS. The operation defined inside the parentheses is always evaluated before the outside operation.

SCSS supports all the mathematical operators required for performing basic mathematical operations: +, -, /, *, %.

example 24: mmathematical operators

        @debug 10s + 15s  // 25s
        @debug 1in - 10px  // 0.8958333333in
        @debug 5px * 3px  // 15px*px
        @debug (12px/4px)  // 3
        @debug 1in % 9px  // 0.0625in
        @debug 50px + 50  // 100px
        @debug 12px * 10  // 120px
    

In SCSS, mathematical operators are meant for performing operation on all units of data used in SCSS, like px, in, etc., along with color Hexa codes.
If you perform any mathematical operation on two Hexa code for colors it will produce some other Hexa code.
Also, we can use the "- operator" to define negative values,like -5px, etc.(make sure there is no space between the - operator and the number if representing a negative value.)
Apart from their basic operations, "+", "-" and "/" operators are also used for string concatenation in SCSS.

example 25: mathematical operators

        .main-division{
            margin: 100px + 200px;
            padding: 1000px / 100px - 10px;
            height: 5px * 3px;
            width: 1in % 9px;
            background-color: #111100+#001111;
        }
    

SCSS supports two equality operators, namely, equal to (i.e. ==) and not equal to (i.e !=). The operators behave differently for values of different types. So we should use them carefully.

If you are comparing two numbers, then they are equal if they have the same value and the same unit or data type. For different units, SCSS performs the conversion automatically if possible.

Colors are equal if they have the same red, green, blue and alpha values.

"true", "false" and "null" data units are only equal to themselves.

Similar rules are followed for complex types like "List" and "Maps". All the values present inside them are compared one by one with each other against value and unit.

example 26: equality operators

        @debug 1px == 1px  // true
        @debug 1px != 1em  // true
        @debug 1 != 1px  // true
        @debug 96px == 1in  // true. SASS performs automatic conversion
    

SCSS supports the following relational operators: "<", ">", "<=", "=>"

example 27: relational operators

        @debug 10 > 5  // true
        @debug 11px < 21px  // true
        @debug 96px >= 1in  // true
        @debug 10px < 17  // true
    

There are no special operators in SCSS for performing string operation. The mathematical operators "+", "-" and "/" when used with strings perform the string operations.

<expression> + <expression> returns a string that contains both expressions’ values. If either value is quoted-string the result will be quoted; otherwise, it will be unquoted.

<expression> / <expression> returns an unquoted string that contains both expression's values, separated by /.

<expression> - <expression> returns an unquoted string that contains both expression's values, separated by -. This is a legacy operator but still works.

.

example 28: string operators

        font-family: "Arial" + " Helvetica" + " sans-serif";  // output will be Arial, Helvetica, sans-serif
        font-size: 10px / 5px;   // output will be 10px/5px and not 2 px
        font-family: sans-+serif;   // output will be sans-serif
        font-family: sans - serif;   // output will be sans-serif
    

Logical operators - such as "and", "or", and "not" - are also available in SCSS.

not <expression> returns the negation or opposite of the value of the expression provided.

<expression> and <expression> returns "true" if the values of both the left expression and the right expression are true, and "false" if either is false.

<expression> or <expression> returns "true" if either expression's value is true, and "false" if both are false.

example 29: logical operators

        @debug not true; // false
        @debug not false; // true
        @debug true and true; // true
        @debug true and false; // false
        @debug true or false; // true
        @debug false or false; // false
    

interpolation

top

SCSS interpolation is a technique to include the result of any SCSS script expression into the stylesheet wherever required. This can be used to define any style rule property, dynamic variable names, dynamic function names, etc. in your SCSS style code.

syntax:#{} /*anything inside will be evaluated*/

example 30: SCSS interpolation

        @mixin corner-icon($name) {
            /* using interpolation */
            .icon-#{$name} {
              background-image: url("/icons/#{$name}.svg");
            }
        }
        /* calling the above mixin */
        @include corner-icon("mail");
    

This will be compiled into the following CSS code:

        .icon-mail {
            background-image: url("/icons/mail.svg");
        }