CSS - Loops

CSS Loops – Complete Guide with SASS & SCSS Examples

Loops in CSS

Introduction to CSS Loops

CSS by itself does not support traditional programming loops like for, while, or do-while. However, modern CSS development often relies on preprocessors such as SASS and SCSS, which introduce powerful features including CSS loops. These loops allow developers to generate repetitive CSS code efficiently, improve maintainability, and reduce errors in large-scale projects.

In this detailed guide, you will learn everything about CSS loops, how loops work in SASS and SCSS, and how to use them effectively in real-world projects. This learning-focused content is structured clearly for beginners and intermediate learners, making it ideal for educational platforms.

Primary Keywords Used in This Content

  • CSS Loops
  • SASS Loops
  • SCSS Loops
  • CSS Preprocessor Loops
  • Loops in CSS

Why CSS Needs Loops

Traditional CSS follows a declarative approach, which means styles are written explicitly. While this is simple for small projects, it becomes repetitive and difficult to manage in large applications. Consider scenarios such as:

  • Creating multiple utility classes with incremental values
  • Generating grid systems
  • Defining repeated animations
  • Managing spacing, typography scales, or color variations

Without loops, developers would need to write hundreds of repetitive lines manually. CSS preprocessors solve this problem by introducing loops that generate CSS dynamically during compilation.

Understanding CSS Preprocessors

A CSS preprocessor is a tool that extends CSS with advanced features such as variables, nesting, mixins, functions, and loops. The most popular CSS preprocessors are:

  • SASS (Syntactically Awesome Stylesheets)
  • SCSS (Sassy CSS)
  • LESS

SASS and SCSS are the most widely used and provide robust loop mechanisms. SCSS syntax is especially popular because it closely resembles standard CSS.

Types of Loops in SASS and SCSS

SASS and SCSS support three main types of loops:

  • @for loop
  • @each loop
  • @while loop

Each loop serves a specific purpose and is useful in different situations. Let us explore them in detail.

@for Loop in CSS (SASS/SCSS)

The @for loop is used when you know the exact number of iterations required. It is commonly used for generating numbered classes, grid columns, or spacing utilities.

Syntax of @for Loop


@for $i from 1 through 5 {
  .item-#{$i} {
    width: 20%;
  }
}

Explanation

In this example:

  • $i is the loop variable
  • from 1 through 5 means the loop runs from 1 to 5 inclusive
  • #{$i} is interpolation used to create dynamic class names

Generated CSS Output


.item-1 { width: 20%; }
.item-2 { width: 20%; }
.item-3 { width: 20%; }
.item-4 { width: 20%; }
.item-5 { width: 20%; }

Using "to" vs "through"

SASS provides two variations:

  • to – excludes the last value
  • through – includes the last value

@for $i from 1 to 5 {
  .box-#{$i} {
    height: 50px;
  }
}

This loop will generate classes from .box-1 to .box-4.

@each Loop in CSS

The @each loop is used to iterate over lists or maps. It is extremely useful when working with predefined values such as colors, font sizes, or breakpoints.

Basic @each Loop Example


$colors: red, green, blue;

@each $color in $colors {
  .text-#{$color} {
    color: $color;
  }
}

Generated CSS


.text-red { color: red; }
.text-green { color: green; }
.text-blue { color: blue; }

Using @each with Maps

Maps allow key-value pairs, making CSS loops more powerful.


$font-sizes: (
  small: 12px,
  medium: 16px,
  large: 20px
);

@each $name, $size in $font-sizes {
  .font-#{$name} {
    font-size: $size;
  }
}

Generated Output


.font-small { font-size: 12px; }
.font-medium { font-size: 16px; }
.font-large { font-size: 20px; }

@while Loop in CSS

The @while loop is used when the number of iterations is not fixed and depends on a condition. It is less commonly used but still useful in specific scenarios.

Syntax of @while Loop


$i: 1;

@while $i <= 5 {
  .margin-#{$i} {
    margin: #{$i * 10}px;
  }
  $i: $i + 1;
}

Explanation

The loop continues running until the condition becomes false. Be cautious when using @while loops, as incorrect conditions can lead to infinite loops during compilation.

Real-World Use Cases of CSS Loops

Creating Grid Systems

CSS loops are widely used to create grid systems similar to popular frameworks.


@for $i from 1 through 12 {
  .col-#{$i} {
    width: (100% / 12) * $i;
  }
}

Spacing Utility Classes


@for $i from 0 through 10 {
  .m-#{$i} {
    margin: #{$i * 5}px;
  }
}

Button Variations


$btn-colors: primary, secondary, success;

@each $btn in $btn-colors {
  .btn-#{$btn} {
    padding: 10px 20px;
  }
}

Benefits of Using CSS Loops

  • Reduces repetitive code
  • Improves maintainability
  • Enhances scalability
  • Ensures consistency across styles
  • Saves development time

CSS Loops vs JavaScript Loops

CSS loops generate styles at compile time, while JavaScript loops manipulate styles at runtime. CSS loops are best for static style generation, whereas JavaScript loops are suitable for dynamic behavior.

Future of CSS and Loops

Native CSS is evolving with features like custom properties and container queries. While native loops are not yet available, preprocessors remain essential for scalable CSS architecture.


CSS loops using SASS and SCSS are powerful tools that help developers write clean, scalable, and efficient stylesheets. By mastering @for, @each, and @while loops, you can significantly improve your CSS workflow and maintain large projects with ease. This knowledge is essential for modern front-end development and highly valuable for learners and professionals alike.

logo

CSS

Beginner 5 Hours
CSS Loops – Complete Guide with SASS & SCSS Examples

Loops in CSS

Introduction to CSS Loops

CSS by itself does not support traditional programming loops like for, while, or do-while. However, modern CSS development often relies on preprocessors such as SASS and SCSS, which introduce powerful features including CSS loops. These loops allow developers to generate repetitive CSS code efficiently, improve maintainability, and reduce errors in large-scale projects.

In this detailed guide, you will learn everything about CSS loops, how loops work in SASS and SCSS, and how to use them effectively in real-world projects. This learning-focused content is structured clearly for beginners and intermediate learners, making it ideal for educational platforms.

Primary Keywords Used in This Content

  • CSS Loops
  • SASS Loops
  • SCSS Loops
  • CSS Preprocessor Loops
  • Loops in CSS

Why CSS Needs Loops

Traditional CSS follows a declarative approach, which means styles are written explicitly. While this is simple for small projects, it becomes repetitive and difficult to manage in large applications. Consider scenarios such as:

  • Creating multiple utility classes with incremental values
  • Generating grid systems
  • Defining repeated animations
  • Managing spacing, typography scales, or color variations

Without loops, developers would need to write hundreds of repetitive lines manually. CSS preprocessors solve this problem by introducing loops that generate CSS dynamically during compilation.

Understanding CSS Preprocessors

A CSS preprocessor is a tool that extends CSS with advanced features such as variables, nesting, mixins, functions, and loops. The most popular CSS preprocessors are:

  • SASS (Syntactically Awesome Stylesheets)
  • SCSS (Sassy CSS)
  • LESS

SASS and SCSS are the most widely used and provide robust loop mechanisms. SCSS syntax is especially popular because it closely resembles standard CSS.

Types of Loops in SASS and SCSS

SASS and SCSS support three main types of loops:

  • @for loop
  • @each loop
  • @while loop

Each loop serves a specific purpose and is useful in different situations. Let us explore them in detail.

@for Loop in CSS (SASS/SCSS)

The @for loop is used when you know the exact number of iterations required. It is commonly used for generating numbered classes, grid columns, or spacing utilities.

Syntax of @for Loop

@for $i from 1 through 5 { .item-#{$i} { width: 20%; } }

Explanation

In this example:

  • $i is the loop variable
  • from 1 through 5 means the loop runs from 1 to 5 inclusive
  • #{$i} is interpolation used to create dynamic class names

Generated CSS Output

.item-1 { width: 20%; } .item-2 { width: 20%; } .item-3 { width: 20%; } .item-4 { width: 20%; } .item-5 { width: 20%; }

Using "to" vs "through"

SASS provides two variations:

  • to – excludes the last value
  • through – includes the last value
@for $i from 1 to 5 { .box-#{$i} { height: 50px; } }

This loop will generate classes from .box-1 to .box-4.

@each Loop in CSS

The @each loop is used to iterate over lists or maps. It is extremely useful when working with predefined values such as colors, font sizes, or breakpoints.

Basic @each Loop Example

$colors: red, green, blue; @each $color in $colors { .text-#{$color} { color: $color; } }

Generated CSS

.text-red { color: red; } .text-green { color: green; } .text-blue { color: blue; }

Using @each with Maps

Maps allow key-value pairs, making CSS loops more powerful.

$font-sizes: ( small: 12px, medium: 16px, large: 20px ); @each $name, $size in $font-sizes { .font-#{$name} { font-size: $size; } }

Generated Output

.font-small { font-size: 12px; } .font-medium { font-size: 16px; } .font-large { font-size: 20px; }

@while Loop in CSS

The @while loop is used when the number of iterations is not fixed and depends on a condition. It is less commonly used but still useful in specific scenarios.

Syntax of @while Loop

$i: 1; @while $i <= 5 { .margin-#{$i} { margin: #{$i * 10}px; } $i: $i + 1; }

Explanation

The loop continues running until the condition becomes false. Be cautious when using @while loops, as incorrect conditions can lead to infinite loops during compilation.

Real-World Use Cases of CSS Loops

Creating Grid Systems

CSS loops are widely used to create grid systems similar to popular frameworks.

@for $i from 1 through 12 { .col-#{$i} { width: (100% / 12) * $i; } }

Spacing Utility Classes

@for $i from 0 through 10 { .m-#{$i} { margin: #{$i * 5}px; } }

Button Variations

$btn-colors: primary, secondary, success; @each $btn in $btn-colors { .btn-#{$btn} { padding: 10px 20px; } }

Benefits of Using CSS Loops

  • Reduces repetitive code
  • Improves maintainability
  • Enhances scalability
  • Ensures consistency across styles
  • Saves development time

CSS Loops vs JavaScript Loops

CSS loops generate styles at compile time, while JavaScript loops manipulate styles at runtime. CSS loops are best for static style generation, whereas JavaScript loops are suitable for dynamic behavior.

Future of CSS and Loops

Native CSS is evolving with features like custom properties and container queries. While native loops are not yet available, preprocessors remain essential for scalable CSS architecture.


CSS loops using SASS and SCSS are powerful tools that help developers write clean, scalable, and efficient stylesheets. By mastering @for, @each, and @while loops, you can significantly improve your CSS workflow and maintain large projects with ease. This knowledge is essential for modern front-end development and highly valuable for learners and professionals alike.

Related Tutorials

Frequently Asked Questions for CSS

Content, padding, border, and margin make up the box model.

Relative moves from original position; absolute positions relative to nearest positioned ancestor.

id is unique; class can be reused.

visibility hides but keeps space; display removes element from layout.

Minify files, reduce specificity, and remove unused styles.

Overrides all other declarations, regardless of specificity.

Use margin: auto or flexbox/grid techniques.

Allow responsive design by applying styles based on screen size or device.

Define relationships between selectors: descendant ( ), child (>), adjacent (+), sibling (~).

Tools like SASS or LESS add features like variables and nesting to CSS.

Targets part of an element, like ::before or ::after.

Use @import "filename.css"; at the top of the file.

Controls stacking order of overlapping elements.

Forces a property to inherit value from parent.

Static β€” not affected by top, bottom, left, or right.

Use universal selector * or define styles in body/root.

em is relative to parent; rem is relative to root element.

Inline, internal (embedded), and external CSS.

A layout model for arranging elements in rows or columns with flexible sizing.

Targets elements in a specific state, like :hover or :nth-child().

Use fluid layouts, media queries, and relative units.

CSS styles HTML elements to control layout, color, fonts, and responsiveness.

Reusable custom property values, declared with --var-name.

Determines which rule applies when multiple rules target the same element.

Performs calculations to dynamically set CSS property values.

line

Copyrights © 2024 letsupdateskills All rights reserved