Yogesh Chauhan's Blog

How to use @each rule with key-value pair in SCSS?

in SCSS on July 20, 2021

For each loop is similar to a for loop in SassScript.

You can also use @each rule to iterate over each key and value pair in a map.

Syntax


@each $key, $value in $list {
  ...
}

Can you use $value first and then $key second?

NO.

SassScript will assign the value of key to the first variable and value to the second variable.

I have used $key just for simplicity purposes. It can be any variable.

Example


$widths: ("full": "100%", "half": "50%");

@each $width, $percent in $widths {
  .img-#{$width}{
     width: $percent;
  }
}

The code above will compile into this CSS:


.img-full{
  width: 100%;
}

.img-half{
  width: 50%;
}

What about a list of lists?

SassScript calls it destructuring when you use @each rule with a list of lists.

When you use @each rule with a list of lists, it automatically assigns values from the list to each variables specified.

The order is important since the first variable will be assigned the first value and so on.

What if the inner list is missing values?

Then a null value will be assigned to the variable in place.

Example


$sizes: 
  "full" "100%" "auto", 
  "half" "50%" "300px";

@each $size, $width, $height in $sizes {
  .img-#{$size}{
     width: $width;
     height: $height;
  }
}

The code above will be compiled into this CSS:


.img-full{
  width: 100%;
  height: auto;
}

.img-half{
  width: 50%;
  height: 300px;
}


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Short-Circuit Evaluation in JavaScriptJavaScriptWordPress plugin development: How to fix a SQL injection?WordPressHow to retrieve homepage URL in WordPress?WordPressSlider animation using CSS transform propertyCSSHow to render lists inside a component in React?ReactWhat’s new in Constructor in PHP 8?PHP