Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Aurelian Spodarec
Aurelian Spodarec
10,801 Points

Refactoring this , how?

A better way to do this?

@mixin mq($breakpoint) {
  @if $breakpoint == "xs-up" {
    @media (min-width: 580px) {
      @content;
    }
  }

  @else if $breakpoint == "xs-only" {
    @media (min-width: 1px) and (max-width: 580px) {
      @content;
    }
  }

  @else if $breakpoint == "small" {
    @media (min-width: 580px) and (max-width: 767px){
      @content;
    }
  }

  @else if $breakpoint == "small-below" {
     @media (max-width: 580px){
      @content;
    }
  }

  @else if $breakpoint == "small-up" {
     @media (min-width: 580px){
      @content;
    }
  }

  @else if $breakpoint == "medium-up" {
    @media (min-width: 767px) {
      @content;
    }
  }

   @else if $breakpoint == "medium" {
    @media (min-width: 767px) and (max-width: 1100px) {
      @content;
    }
  }

  @else if $breakpoint == "medium-below" {
    @media (max-width: 767px){
      @content;
    }
  }

  @else if $breakpoint == "large-up" {
    @media (min-width: 1100px) {
      @content;
    }
  }

  @else if $breakpoint == "large-below" {
    @media (max-width: 1100px){
      @content;
    }
  }
}

1 Answer

Joel Bardsley
Joel Bardsley
31,249 Points

EDITED - Looks like this doesn't work for breakpoints that have both min-width and max-width values, but it might help anyway

You could use a Sass Map to set your breakpoint names as keys with corresponding pixel values ie:

$breakpoints: (
  'xs-up'  : (min-width: 580px),
  'xs-only' : (min-width: 1px) and (max-width: 580px),
  'small'  : (min-width: 580px) and (max-width: 767px)
);

Then on your mixin, you can set a single if statement to check whether the breakpoint key exists, and providing a warning message if it doesn't:

@mixin mq($name) {
  // If the key exists in the map
  @if map-has-key($breakpoints, $name) {
    // Prints a media query based on the value
    @media #{inspect(map-get($breakpoints, $name))} {
      @content;
    }
  }

  // If the key doesn't exist in the map
  @else {
    @warn "Unfortunately, no value could be retrieved from `#{$breakpoint}`. "
        + "Please make sure it is defined in `$breakpoints` map.";
  }
}

The inspect, map-has-key and map-get functions are built-in sass functions if you want to refer to the documentation

Hope that helps.