Sass Media Query Mixins

There are a few Sass media query mixins going around for dealing with old versions of IE. Often they include predefined break points, whereas I like the simplicity of passing a numeric value.

Capable browsers wrap the content in a media query, incapable browsers get the unwrapped content.

$is_ie8_file: false !default;
@mixin mq-minwidth( $minWidth ) {
  // in modern browsers, wraps content in the media query:
  // @media ( min-width : $minWidth )
  // in oldie, just displays the content
	
  @if ( true == $is_ie8_file ) {
    @content;
  } @else {
    @media ( min-width: $minWidth ) {
      @content;
    }
  }
}

I know max-width media queries are bad, but I’m pragmatic enough to know that a mixin to deal with them is handy to have. By default, I leave the content out of oldie, as the point of the mixins is to give oldie the desktop layout.

@mixin mq-maxwidth( $maxWidth, $include_in_ie8: false ) {
  // in modern browsers, wraps content in the media query:
  // @media ( max-width : $maxWidth )
  // in oldie, the content is not included unless
  // the second variable is passed as true.
	
  // using max-width media queries is less than ideal
  // as browsers may download resources they do not need.
  // The browsers using the max-width media queries are 
  // often phones on bandwidth limited networks.

  @if ( true == $is_ie8_file ) {
    @if ( true == $include_in_ie8 ) {
      @content;
    }
  } @else {
    @media ( max-width: $maxWidth ) {
      @content;
    }
  }
}

Making use of the mixins requires two files, the standard file for modern browsers and a second file for older browsers. The standard files has no special requirements, the oldie file must start by setting the variable $is_ie8_file: true.

Following the setup, it’s a simple case of using conditional comments to point browsers to the appropriate compiled file:

<!--[if (lte IE 8)&!(IEMobile) ]>
  <link rel="stylesheet" href="style-ie8.css" />
<![endif]-->
<!--[if (gt IE 8)|(IEMobile)]><!-->
  <link rel="stylesheet" href="style.css" />
<!--<![endif]-->

Updates

September 17, 2014: Changed conditional comments to account for mobiles.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.