dots Created with Sketch.
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;
}

amazon

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

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
Accessing and Setting features of JavaScript ObjectsJavaScriptPHP arrays for US states’ full names and abbreviationsPHPLearn to Make a Simple Contact Us Form using PHP and PDO-MySQLPHPEXISTS and NOT EXISTS in PostgresPostgresHow to change the style for checked radio button or checkboxes using CSS?CSSWhat is a component helper function in React?React