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 automatically.

You’ll notice in the code that we wrap the variable selector name in #{}, which we learned about in the previous task.

What To Do...
  • Copy one style to many variables with @each.
    advanced/ateach.scss
     
    @each​ $​member​ ​in​ ​thom​, ​jonny​, ​colin​, ​phil​ {
     
    .#{$member}_picture {
     
    background-image: ​url("/image/#{$member}.jpg")​; } }

    This compiles to:

     
    .thom_picture {
     
    background-image: ​url("/image/thom.jpg")​; }
     
     
    .jonny_picture {
     
    background-image: ​url("/image/jonny.jpg")​; }
     
     
    .colin_picture {
     
    background-image: ​url("/image/colin.jpg")​; }
     
     
    .phil_picture {
     
    background-image: ​url("/image/phil.jpg")​; }

Related Tasks

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.17.91