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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
3 ways to pass a variable in url() function in SCSS (Sass)SCSSLearn to create your skill bar using CSSCSSHow to load a module with configuration in SCSS?SCSSHow to modify navigation menus in WordPress?WordPress3 JavaScript methods to use when you want to go back and forth in historyJavaScriptHow to float an image around texts?CSS