SCSS - Loop a list starting at key 2

Viewed 234

If I have a list as follows:

$breakpoints: (
  all: all,
  xl: 1200,
  lg: 1037,
  md: 797,
  sm: 615,
  xs: 415,
);

In an @each is there any way to loop through the list but either first remove the first key, or start at key 2?

3 Answers

I can think of two ways to achieve that.

1. With a @each loop

In this loop, I'll check if the value is equal to "all", if it is, I'll do nothing and continue my loop.
It works well, but if you decide to change "all" with some other name, you'll need to update the loop.

@each $key, $value in $breakpoints {
  @if ($value == "all") {} // If the value == all, do nothing
  @else {
    @media screen and (max-width: $value) {
      /* Your fancy code */
    }
  }
}

2. With a @for loop

In this loop, I'll go through the length of $breakpoints starting from 2.
Then, I'll retrieve the value according to the index.

@for $i from 2 through (length($breakpoints)) {
    $breakpoint : nth($breakpoints, $i);
    $value : nth($breakpoint, 2);
    @media screen and (max-width: $value) {
      /* Your fancy code */
    }
}

EDIT

It can be even easier with the @each loop:

@each $key, $value in $breakpoints {
  $i: index($breakpoints, $key $value);
  @if ($i != 1)
  {
    @media screen and (max-width: $value) {
      /* Your fancy code */
    }
  }
}

You can skip the first entry using map-remove (note I added * 1px) to get unit values :)

This will not mutate the $breakpoints map

@each $key, $value in map-remove($breakpoints, all) {
    @media (max-width: $value * 1px){
        // dummy content printing out the breakpoint
        body::before { content: '#{$key}' }
    }
}
Related