Johan Johan - 2 months ago 17
Sass (Sass) Question

Combining media query statements

I'm creating a media query helper with SASS. I need your help getting the

medium
breakpoint working.

Right now it's only printing the max-width. Any ideas why?

$breakpoints: (
small: ( max-width: 767px ),
medium: (min-width: 768px ) and ( max-width: 991px ), // <--
large: ( min-width: 1200px )
);

@mixin respond-to($name) {
@if map-has-key($breakpoints, $name) {
@media #{inspect(map-get($breakpoints, $name))} {
@content;
}
}
@else {
@warn "no match found in breakpoint map";
}
}

Answer

Sass tries to calculate boolean value of (min-width: 768px ) and ( max-width: 991px ) and gets error. So you should set breakpoints as strings.

Sass:

$breakpoints: (
  small:  '( max-width: 767px )',
  medium: '( min-width: 768px ) and ( max-width:  991px )',
  large:  '( min-width: 1200px )'
);

@mixin respond-to($name) {
  @if map-has-key($breakpoints, $name) {
    @media #{map-get($breakpoints, $name)} {
      @content;
    }
  } @else {
    @warn "no match found in breakpoint map";
  }
}

a {
  @include respond-to(medium) {
    color: red;
  }
}

Css output:

@media (min-width: 768px) and (max-width: 991px) {
  a {
    color: red;
  }
}

Sassmeister demo.