Always Twisted

{ Slightly Bizarre Ramblings Of A Front-End Developer }

A Sass mixin for media queries and IE

I'm currently finishing up some front-end co-coding for a client who hired me for all the mobile/responsive goodness. As well as this they wanted me to instigate and create the CSS using Sass/SCSS. Near the end of the project they asked how we would support IE8/7/6.

We did discuss this at the start of the project but carried on with 'all the things'. I had seen all the hotness around Sass 3.2 that would allow you to create a respond-to mixin. So decided to upgrade my Sass gem to the latest version and updated all my 'hand coded' media queries with the relevant Sass/SCSS mixins.

This was great, kinda, it now took the px/em value out of the CSS and allowed me to change it in my Sass settings/mxins/variables file but it did not let me create a fallback for internet explorer. 

Here is the SCSS and the CSS I wanted/expected.

The SCSS setup


// Setting up a quick respond-to mixin
@mixin respond-to($name) {
  @if $name == tablet {
    @media only screen and (min-width: 768px) { @content; }
  }
}

// So this is the mixin that I'm currently using

@mixin this-is-what-i-want($name. $ie-class) {
  ie-class-here { @content; }
  media-query-here } @content; }
}

The SCSS file


// This is how I include the mixin within my SCSS file

.foo {
  margin: 0 auto;
  padding: 0 10px;§
  
  @include this-is-what-i-want(tablet, lt-ie9) {
    min-width: 940px;
    max-width: 1220px;
    padding: 0 20px;
  }
}

My 'wished for' CSS output


.foo {
  margin: 0 auto;
  padding: 0 10px;§
}

.lt-ie9 .foo {
    min-width: 940px;
    max-width: 1220px;
    padding: 0 20px;
}

@media only screen and (min-width: 768px) {
    .foo {
        min-width: 940px;
        max-width: 1220px;
        padding: 0 20px;
     }
}

To The Internets

So I started crawling the gists on gitub to see if anyone had created a little code snippet just for this reason. I didn't. There was nothing. So I quickly asked some really, clever and amazing people on the twitters and I got this bit of code from the fantastic @snugug.


mixin respond-wrapper-fallback($name, $wrapper-class) {
  .#{$wrapper-class} & {
    @content;
  }
  @include respond-to($name) {
      @content;
    }
  }

This now turns my 'wished for' CSS output into a reality and now means I can create a fallback for Internet Explorer from 'whatever' CSS Media Query block I need.

To skin a cat.

There's more than one solution for patching up code for Internet Explorer using Sass. This is the solution I required. Jake Archibald created a IE-friendly mobile-first solution which I shall be likely to use at the start of future projects and there's Nicolas' solution also.

 

Did you like this post? Hire me.
blog comments powered by Disqus