HTML & CSS
Article

An Introduction to Mobile-First Media Queries

By Chris Poteet

There is no denying the influence of responsive approaches in our design and implementation efforts. What was once new and unknown is now the assumed standard. When I started down the path of understanding the impact of responsive web design, I had an easy time finding out how to do something with media queries, but I had a harder time finding out why I should do it a certain way. This article is an attempt to remedy this situation.

My intent is that it will serve as a helpful introduction for those of you attempting to understand the massive implications of the mobile-first approach and for those more experienced with the approach it can serve as a good refresher.

I will focus on the details of writing mobile-first media queries, and this will also include why we should do this and close with guidance for starting out. However, first we should look at some important distinctions in the phrase “mobile-first”.

Shades of Mobile-First

It is important for our discussion to distinguish that “mobile-first” has two distinct senses. Some might see this as unnecessary, but for the guidance I will share at the end of the article it is important.

Many are familiar with the philosophical approach put forth by Luke Wroblewski in his book entitled Mobile First. Luke writes about the design advantages of a mobile-first strategy, the biggest impact being the imposed constraints of mobile devices that force us to focus on the essentials. He also talks about how mobile devices have capabilities that allow us to enhance the experience (e.g. GPS, accelerometer, etc.). This is what I will refer to as mobile-first design.

However, this is not the only sense, and this article will focus on the second sense. The second sense I will refer to as mobile-first implementation. This uses the technical tenets of responsive design, as coined by Ethan Marcotte. This means that when we actually implement the interface (prototype or production), we start out designing at the smallest viewport possible (which we will call a “mobile viewport,” but someday this might be “watch viewport” as the smallest) and we then progressively add styles and sometimes other enhancements as the viewport increases.

Let’s now look at the how and the benefits of mobile-first media queries.

Creating Mobile-First Media Queries

Rather than explaining all the ins and outs of media queries in this section, I want to focus specifically on how the technique is technically accomplished. Let’s look at two different media queries and dissect their implementation. Please note that I’m keeping this simple so I will avoid any specific class naming structure or style.

.sidebar {
  float: left;
  width: 25%;
}

.content {
  float: left;
  width: 75%;
}

@media (max-width: 40em) {
  .sidebar, .content {
     float: none;
     width: auto;
  }
}

You can see this simple example at work in this CodePen demo. Resize the window to see the change take place.

In this sample, I have two elements that are using floats so that they are lined up horizontally, and I have percentage-based widths on both of them. Then I have a media query breakpoint where the floats are disabled and the width is restored to full width using the “auto” value.

What are the problems with this approach?

  1. It forces us to “undo” styles through our media queries. This is not an efficient approach to managing your styles, but we should instead be adding styles.
  2. Our original float styles go against the natural flow of HTML elements. Block elements naturally clear on the top and bottom and flow at 100%, so the “undo” styles are merely declaring explicitly what the elements already do naturally.
  3. This does not allow us to embrace the same constraints that we may have used in our mobile-first design. We essentially are going in two different philosophical directions.

You can usually spot the implementations that start at large viewports and go down by the presence of “max-width” in the media queries. This is not always the case, but it is usually a pretty strong indicator. Now let’s look at another example:

@media (min-width: 40em) {
  .sidebar {
     float: left;
     width: 25%;
  }

  .content {
     float: left;
     width: 75%;
  }
}

Now let’s look at the advantages of this model, which are really the opposite of the problems we started with above (a demonstration of this is on CodePen as well).

  1. Instead of undoing the floats as we go down, we only need to add the floats when we need them. This reduces a lot of unnecessary CSS.
  2. In this instance we are taking what HTML gives us by default and not going against it unnecessarily. By default, browsers us give us what we want and need in smaller viewport so we utilize those defaults (i.e. block elements are set to width: auto by default).
  3. Using this method we are philosophically on the same page of our mobile-first design.

Source Ordering: A More Complex Example

The example above is very simple and on purpose, but let’s look at a more complex example. One of the first things you will learn about and have to deal with is the problem of DOM source ordering.

Source ordering refers to how a document is rendered as a result of the DOM structure. The DOM renders top to bottom, and until the advent of flexbox we didn’t have a pure CSS method to decouple rendering from source order. Even though flexbox is exciting, we will never get away from considering source order as we create responsive interfaces.

In this third CodePen example you can see priority highlighted from left to right.

Source ordering is a very important concept to understand as you move into responsive web design. From the example above you can see when the viewport dips below 40em the most important content (labeled “first priority”) is on top. This is what we want to happen given the importance of limited space in small viewports.

Now you could get something similar in the desktop-down implementation, but what I’ve seen people do is fall into old tendencies of not thinking first about the importance of source ordering. Mobile-first design and implementation makes it an inescapable reality, and when these are paired together the result is a powerful solution. Then technologies like flexbox can be used as an enhancement when needed if the need to change the rendering order exists.

A Couple More Advantages

The mobile-first code above is a great example of responsible implementation through progressive enhancement. It is important to note that there are still old mobile browsers that do not support media queries, and it is helpful that they will receive the smaller viewport layout. There are other browsers that have issues with media queries, most importantly IE8 and below. You can polyfill media queries, or use a preprocessor solution.

Brad Frost on the advantages of mobile-first

Mobile-First implementation is more efficient and future-friendly (Image credit)

There is another important benefit to structure our media queries in this way, and that is performance. Tim Kadlec has done the research to show that using media queries in this manner can avoid unnecessary downloads. So, for instance, if you wanted to add a background image only at larger viewports or even swap out a smaller for a larger one, you save downloads and loading time. If I were to add an image to my sidebar in the example above, it would download and show up only when the viewport reaches at least 40em.

Manage Your Media Queries with Sass

Before I conclude, I recommend that you use a preprocessor to help you manage your media queries. There are countless options and even preprocessor syntaxes for handling this (Sass, Less, Stylus). I prefer a simpler approach and Chris Coyier has demonstrated a Sass mixin that I use in my projects. I will update it to use my preferred language.

@mixin mquery($size) {
  if $size == small {
    @media (min-width: 30em) {
      @content; 
    }
  }

  else if $size == medium {
    @media (min-width: 40em) {
      @content;       
    }
  }
}

Then we can reference it this way.

.sidebar, .content {
  @include mquery(medium) {
    float: left;
  }
}

This is great because we can centrally control our media query values, and we can always see how our elements are changing throughout all of our media queries. It used to bother me that my compiled CSS output contained repetitive media query syntax, but with minification and GZIP it is not a big increase. If it really bothers you and you use Grunt then Grunt can combine your media queries after the Sass processing.

Conclusion

When you are ready to go further in your reading and studies, start with 7 Habits of Highly Effective Media Queries, a great post by Brad Frost.

This article was meant to be a quick primer on the definitions, approach, and benefits to using mobile-first media queries. I wish you all the best as you continue to grow and embrace these new and exciting approaches that help better serve our clients and customers.

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

Comments
bella_Angel

Hi..
thanks for sharing your valuable insight with us.Grateful for giving such informational article.. Let me if you any such more tutorials.

chronicler_isiah

Of course this is all fine and dandy when you're building a site from scratch. In that instance then yes work using mobile first (until the next trend comes along).

But, if you're in the position of working on a legacy site(s) trying to drag them kicking and screaming into the responsive age, then it's far less hassle as far as css writing is concerned, to go down the max-width route.

It's easy in that you simply add as many max-width breakpoints you need to suit your current design. Whereas min-width would require a complete ground up rewrite with all the potential errors that might possibly creep in.

And I'm not convinced that either method is greatly noticeably more (or less) efficient from a rendering point of view to worry about the difference. Good optimised css is good optimised css whichever way you go. (Unless of course Google decides to penalise the max-width css-driven sites at some future point.)

Am I bad for saying this? smile

Cheers.

PaulOB

No, I also prefer the max-width approach as I mainly work with client designed PSDs showing the desktop layout so its far easier to start with that and work downwards for smaller screens.

I also find it easier to work out how to make the desktop site scale into mobile than the other way around.:)

RyanReese

+1 on this. I have never done mobile-first designs. I think they are mainly popular due to frameworks and it's easier to start from bottom up for the mass populus. Probably a few other reasons but nothing that makes desktop-down a disadvantage.

I disagree that it's supposedly more code to do desktop-down. It's simply backwards. Heck - fluid design incorporated you can actually probably do it in less code. Probably just depends on your planning and your general skill. I see so many people fling 20 media queries at a page...why?! Poor architecture.

ChrisPoteet

I would suggest in general staying away from desktop first design compositions and full compositions in general. Use PSDs as a tool to set the tone but not as a client deliverable. Try designing in the browser.

ChrisPoteet

It is actually much harder to start from the bottom up. I did show how you have to "undo" styles with desktop down which does lead to more, unecessary code.

ChrisPoteet

Agreed that it would require a rewrite. Retrofitting is really the only good case for going large size then down. Then again, it is in my mind a very good reason to redesign.

RyanReese

According to your implementation of the CSS. Whose to say a better person at CSS couldn't clean that up and make it more robust? You aren't used to desktop-down - you don't do it.

ChrisPoteet

Then "clean up" my example. Show me how to do an even moderately complex UI, use max width queries, and try to write less code than a mobile-first way. It can't be done.

RyanReese

Which example? I see this

@PaulOB can get in on this too since he also follows desktop-down design.

ChrisPoteet

Sure that will work. Go desktop down and use as much or less markup than I do.

RyanReese

I basically reduced your bloat from

@media (min-width: 40em) {
  .first {
    float: left;
    width: 25%;
  }
  .second {
    float: left;
    width: 50%;
  }
  .third {
    float: left;
    width: 25%;
  }
}

To

@media (max-width: 40em) {
  .first, .second, .third {
    display:block;
  }
}

That was just within 2 minutes. Feel free to see what other savings I took advantage of.

I'll leave it be for now. The code could probably be further cleaned.
As you can see, it's not that hard to easily convert your mobile-first to desktop-first. They are mirrors of each other.

ChrisPoteet

Do you really want to leave around differing block renderings? Leaving the parent with display: table and the children display: block? You're mixing and matching in a way I don't think is very responsible and open to problems. You also forgot the different widths that necessitated the different selectors.

Also notice you are turning on something (display: block) that is native to the element itself. You are 'undoing' something to return it to a native state whereas I didn't have that issue. You're degrading not enhancing the DOM.

RyanReese

That's not an issue. Maybe in your imaginary world it is.

Point being, even if I reset that parent to the default, the code is the same if not less than what you had.

You are trying to insinuate that desktop-down is worse since it does more.

They are mirrors of each other. Your min-width is my max-width. Your imaginary issues about desktop-down are delusional.

If you cannot see this, then perhaps you can stay in your closed little world. I gave the reverse example to yours. If you cannot see how they are the same, then you can certainly have your opinion; it's clear you aren't open to think differently.

Goodbye wink .

PaulOB

Tell that to the agencies who supply me with 3 or 4 psds every week that their graphic designers have created. smile They don't have the time, expertise or inclination to design in the browser which is why they hire me to do the dirty work.

Not everyone works the same way and the approach that you take usually reflects the way that your work is organised. If you are a designer and designing in the browsers then mobile first is fine. I have no issue with mobile first but just prefer the other way around because that's the display I get presented to me. The code is much the same either way not to really matter. I code the PSD in a day and then move on to the next. No Less, no Sass, no problem.:)

nockgeneer

I actually prefer to use a combination of min and max. Crazy? Consider this: when designing your site, you have a set of items in mind that visitors will be able to interact with. For very small screens, some of these may need to be hidden so that just the article or whatever can be seen, or perhaps so that certain sections get moved to the bottom. A big concern is when trying to present tabular data, since the solution on mobile is to turn rows into cards with each data column prefixed with a ::before selector. Are you going to do all that for a mobile screen first before getting your table looking right?

The problem, of course, is complexity and keeping things straight; mixins are great for that. I still use min-width for most things like breaking up linear content and creating more columns, so that's the default for my mixin; that way, I can work on the desktop first just by putting all the layout code within an include. If I find something needs to break earlier or works fine on mobile, I can just move it out of the include without losing context. Then when I look at things on mobile, I can concentrate on finding the issues that are specific to that media and use a 'max-width' version of the mixin for those. Of course, this would probably work the other way too, but I find this approach is the best way to avoid unnecessarily resetting values.

When it comes to responsive sites, I think it's more a question of using a good preprocessor and looking at each objects display requirements as they fit into the site rather than worrying about top-down vs. bottom-up design. Here is my SCSS/SASS mixin with conversions and error-checking. @include mquery { } will creat a medium min-width media query by default. In addition to treating unitless numbers as ems, I also included a standard conversion of px to em so it can be used to cover for programmers who haven't switched over yet. Feel free to remove that line if you want to enforce good programmer habits.

// _global.scss
$breakpoints: (
  small: 24em,
  medium: 56em,
  large: 96em,
  xlarge: 144em
);
 
// _mixins.scss
@mixin mquery($width: 40, $minmax: min) { 
  @if map-has-key($breakpoints, $width) {
    $width: map-get($breakpoints, $width)
  }
  
  @if type-of($width) == "number" {
  @if unitless($width) { $width: $width * 1em }
  @if unit($width) == px { $width: $width / 16px/em }
    @if unit($width) != em {
      @warn "Please use em values for breakpoints.";
	}
    @else {
      @media (#{$minmax}-width: #{$width}) {
        @content;
      }
    }
  }
  @else {
    @warn "The width could not be understood."
        + "Please provide a valid breakpoint.";
  }
}

// _components.scss example
div {
  padding: 0.5em;
  @include mquery(large) {
    float: left;
    width: 35%;
  }
  @include mquery(30, max) {
    display: none;
  }
}

Change the default width to whatever you want. Using this mixin, the code from ChrisPoteet and RyanReese can be cleaned up like so:

.container {
  width: 100%;
  display: table;
}
.container > div {
  padding: 0.5em;
  @include mquery {
    display: table-cell;
  }
}
.first, .third {
  background: PeachPuff;
  @include mquery {
    width: 25%;
  }
}
.second {
  background: MediumAquamarine;
}

or the media query abstracted out (I prefer to compile things semantically, and it's possible to have media queries combined using a preprocessor)

.container {
  width: 100%;
}
.container > div {
  padding: 0.5em;
}
.first, .third {
  background: PeachPuff;
}
.second {
  background: MediumAquamarine;
}
@include mquery {
  .container > div {
    display: table-cell;
  }
  .first, .third {
    width: 25%;
  }
}

In fact, by selecting nth-child instead of using classes, this can be made even more compact! With SASS:

.container {
  width: 100%;
  display: table;
  > div {
    padding: 0.5em;
    background: MediumAquamarine;
    @include mquery {
      display: table-cell;
    }
  }
  :first-child, :last-child {
    background: PeachPuff;
    @include mquery {
      width: 25%;
    }
  }
}

Here is the codepen link:

If you want to go desktop-down, you would need to add two lines of extra reset code (after changing the mixin minmax default to max), here is that with the media query abstracted out so you can see that too:

.container {
  width: 100%;
  display: table;
  > div {
    padding: 0.5em;
    display: table-cell;
    background: MediumAquamarine;
  }
  :first-child, :last-child {
    width: 25%;
    background: PeachPuff;
  }
  @include mquery {
    > div {
      display: block;
    }
    :first-child, :last-child {
      width: 100%;
    }
  }
}

—Easier if you've got your desktop layout already, but it's unnecessary bloat when designing from scratch with this approach, even when you are working from a desktop mockup.

SamA74

And there won't ever be any circumstances where you would need commit this cardinal sin working mobile first?
I think this is more about personal preference. The arguments for and against can be turned on their heads and looked at the other way. Its the same road, just a different direction.

RyanReese

It's a fictitious issue anyway. Not sure why he brought that up as a talking point.

djsmithme

Given that most mobiles (if not all) understand how to use Media Queries and a lot of legacy desktops do not, coupled with the fact that most traffic is still coming from desktops, as it stands there is nothing wrong with designing for desktop first for simple 1-2 step responsive sites. The only real problem with this is you have to account for 3g/mobile networks and find a away of serving your smallest images and media first.

I personally use mobile first because when you start taking into consideration height as well as the width it gets far too messy.

RyanReese

What? There are "legacy" phones that don't support media queries. Just like there are "legacy" browsers that don't support it. Those legacy browsers are under 1% (closer to 0) (IE8 and down) so this argument in itself is...strange. Could you please elaborate? I'm not sure what makes this a point of consideration.

djsmithme

Phones that do not support Media queries include : Old Blackberry phones, Some Windows Mobile and thats about it. We are talking 0.0something% The rest do, and have an eco system where updating the browser is easy.

Desktops and it gets a little harder. IE8 for example (5% http://caniuse.com/#feat=css-mediaqueries, up to 15% on alot of our sites) needs a polyfill so with js disabled it will not work. Not to mention polyfills slow the site down.

RyanReese

My parents have those phones. I know others do too.

Ultimately we are talking 1-2% difference.

http://www.sitepoint.com/browser-trends-june-2015-battle-second-place/

IE6/7/8 COMBINED overall is placing around 3.4%. Considering how hard it is to upgrade phones due to a multitude of reasons, I'd imagine old phones are within 1-2% of that figure.

So maybe it's just me, but that's not even a talking point.

RyanReese

Just an update. Our government website that I work on (hundreds of thousands of hits) is reporting 1.5% usage in IE8.

I'd say that's right equal with legacy mobiles.

SamA74

As many as that? I have (on a much less popular site) 0.85% over the last month. Compared to 4.77% for the same period a year ago.
Old browsers are dying out. Won't be long before we can bin the polyfill.

RyanReese

Are you government though? I'm assuming my market is much different than yours. Also is your website getting a few million hits a month?

I actually figured it'd be closer to 1% but I'm not complaining.

SamA74

No, they are not a like for like comparison at all. It would be a minority, niche interest site with nowhere near so many hits. It has mainly local appeal, though we do get some world-wide visitors too.

Just for fun yesterday, I thought I would try this out. I dug out of a drawer my old Windows Mobile (v2003) Pocket PC Phone, charged it up to see how it handled my desktop first responsive design. Needless to say it looked a mess, but I did not expect anything else, just curious.
But I honestly don't believe that people using phones to browse the web today are using those phones. I know it works OK on Windows Phone 7 which hasn't the best css3 support, so I'm happy enough with that.

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in Front-end, once a week, for free.