22Stop Repeating Yourself with @each

@each is a trick to keep your Sass DRY (the tenet of Don’t Repeat Yourself). It’s a way of copying the same style for a lot of different variables.

Say we have a bunch of pictures, all with similar file URLs. The file URLs can include figures or punctuation, if necessary. We want to use them in the same way in each case but with slightly different classes. Usually, we’d have to write out each selector separately, replacing a single word each time. So much time, effort, and copying/pasting! This is where @each comes to the rescue.

We follow @each with the name of the generic variable we want to use, then with all the members of the group that we want to apply this to. When compiling the CSS, the list forms ...

Get Pragmatic Guide to Sass now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.