📜  for...of...loop - CSS (1)

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

For...of...Loop - CSS

The for...of...loop is a new feature that was introduced in ES6 (ECMAScript 2015) and it allows you to loop through any iterable object.

In CSS, the for...of...loop can be used to iterate through CSS custom properties, which are a new feature that allows you to define your own CSS properties.

Syntax

The syntax for the for...of...loop in CSS is as follows:

@for $variableName, $value in $iterableExpression {
  /* code to be executed */
}
  • $variableName: the name of the variable that will be used to store each value during the iteration
  • $value: the value that is being iterated over, which is stored in the $variableName variable
  • $iterableExpression: an expression that returns an iterable object, such as a list or a map
Example

Here's an example that shows how to use the for...of...loop in CSS to iterate through a set of custom properties:

:root {
  --primary-color: #007bff;
  --secondary-color: #6c757d;
  --success-color: #28a745;
  --danger-color: #dc3545;
}

@for $name, $color in (
  primary: var(--primary-color),
  secondary: var(--secondary-color),
  success: var(--success-color),
  danger: var(--danger-color)
) {
  .btn-#{$name} {
    background-color: $color;
  }
}

This code will generate the following CSS:

.btn-primary {
  background-color: #007bff;
}

.btn-secondary {
  background-color: #6c757d;
}

.btn-success {
  background-color: #28a745;
}

.btn-danger {
  background-color: #dc3545;
}
Conclusion

The for...of...loop in CSS is a powerful feature that allows you to iterate through any iterable object, such as CSS custom properties. It can be a useful tool for creating dynamic styles that can adapt to different situations.