Post

πŸ‘€ SASS Syntax

In the previous post, we learned how to compile SCSS to CSS. Now we will learn how to write SCSS.

You should first know that you can write SASS stylesheets with two syntaxes.

  1. SCSS Syntax
  2. SASS Syntax

Do they differ? Yes, and the table below highlights their variants.

SCSS vs SASS table comparison

To make things more clear, check out this example, which is written twiceβ€”once with SCSS syntax and once with sass syntax.

SCSS vs SASS code Example

When writing SASS or SCSS, you should adhere to these two rules:Β  1-Style Rules.Β  2-at-Style Rules.

Again, you can take an overview look at these rules in the below screenshot.

Style rules and at-rules list

Fear not, we will explain each of these rules in more detail in the following sections, but for now, let’s focus on the five style principles of nesting, variables, interpolation, placeholder selectors, and selector combinators.

1. Variables

Simple Sass variables allow you to use the name rather than the actual value by assigning a value to a name that starts with the letter $.

1
$variableName : value;
  • variableName: any name that doesn’t start with a number or a special character like @.
  • value: any value (lists, strings, numbers, booleans, null, colors)

Example:

1
2
3
4
5
6
7
// We assign a variable
$colorOfHeading: #616165;

// then use it
h3 {
color: $colorOfHeading
}

Keep in mind that the variables:

  • Can only be used as a property value and will throw an error if used as a property name.
  • Is not available outside of its scope.

Example:

1
2
3
4
5
6
7
$propertyName: 'font-size';
$propertyValue: 30px;

h3{
    $propertyName: $propertyValue; // not Valid
     font-size: $propertyValue; // Valid
}

Example:

1
2
3
4
5
6
7
8
$myColor: red; // in global scope
h1{
$myColor: green; // in local scope
color: $myColor; // green
}
p{
color: $myColor; // red
}

The !global flag can be used to make local variables global.

Example:

1
2
3
4
5
6
7
8
$myColor: red;
h1{
$myColor: green !global;
color: $myColor; // green
}
p{
color: $myColor; // green
}

Note: A hyphen and an underscore are equivalent in Sass. $font-size is the same as $font_size

Example:

1
2
3
4
$font-size: 20px;
h2{
font-size: $font_size; // 20px
}

Tip: to fully control the sizes and widths of your styles, use variables in conjunction with expressions.

Example:

1
2
3
4
$full-width: 100%
.col-1 {float: left; width: $full-width / 1}
.col-2 {float: left; width: $full-width / 2}
.col-3 {float: left; width: $full-width / 3}

Example:

1
2
3
$baseFont: 10px;
$paragraphFontSize: 7px;
h3{font-size: $baseFont + $paragraphFontSize}

Because variables cannot be used as a property name, interpolation comes into the picture. In the following articles, interpolation will be covered in more detail.

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.