Academy / Advanced Level: HTML and CSS

CSS Preprocessors: SASS/SCSS

Conditionals and Loops in SCSS

SCSS allows you to use programming logic such as conditionals (@if, @else) and loops (@for, @each, @while) to generate dynamic styles.

Example: Conditional Logic with @if and @else

$theme: light;

body {
@if $theme == light {
background-color: #fff;
color: #000;
} @else {
background-color: #333;
color: #fff;
}
}

In this example:

  • The background and text color change based on the value of the $theme variable.

Example: Looping with @for

@for $i from 1 through 3 {
.column-#{$i} {
width: 100% / $i;
}
}

In this example:

  • The loop creates three column classes (.column-1, .column-2, .column-3), each with different widths.