📜  for in sass - CSS (1)

📅  最后修改于: 2023-12-03 15:15:09.944000             🧑  作者: Mango

For in Sass - CSS

Sass is a preprocessor scripting language that is compiled into CSS. The for loop in Sass is an extremely powerful feature that allows developers to create complex CSS with a few lines of code.

The for Loop

The for loop in Sass is used to loop through a set of values and create styles based on it. There are two ways to use the for loop in Sass.

The @for Rule

The @for rule is used to loop through a set of values and create styles based on it. It follows the following syntax:

@for $variable from <start> through <end> {
  // Styles to be applied
}

Here, $variable is a variable that will hold the current value of the loop. <start> is the starting value of the loop and <end> is the ending value of the loop. The loop will run from <start> to <end>.

Example

@for $i from 1 through 5 {
  .box-#{$i} {
    width: 10px * $i;
  }
}

This will create the following CSS:

.box-1 {
  width: 10px;
}
.box-2 {
  width: 20px;
}
.box-3 {
  width: 30px;
}
.box-4 {
  width: 40px;
}
.box-5 {
  width: 50px;
}
The @each Rule

The @each rule is used to loop through a list and create styles based on it. The list can contain any type of values, including numbers, strings, and CSS selectors. It follows the following syntax:

@each $variable in <list> {
  // Styles to be applied
}

Here, $variable is a variable that will hold the current value of the loop. <list> is the list that needs to be looped through.

Example

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

This will create the following CSS:

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

The for loop in Sass is an extremely powerful feature that can be used to create complex CSS with a few lines of code. The @for and @each rules are the two ways to use the for loop in Sass.