How to Use CSS3 Media Queries for Mobile First Responsive Designs

What are CSS3 media queries and how can we use them to create responsive web designs? This tutorial shows you how to use CSS3 Media Queries.

By Tim Trott | HTML & CSS Tutorials | December 18, 2015
2,184 words, estimated reading time 8 minutes.

CSS3 introduced media queries into the web development world. Media queries are the foundation for responsive design. They let you create layouts specific to screen sizes such as tablets and smartphones. This article provides you with a brief overview of media queries with the basic syntax for common screen sizes.

I've talked a lot about why responsive web design is important but so far I haven't shown how to use these new CSS3 media queries to create a responsive design, so let me take this opportunity to show you how you can create a responsive design in these simple steps.

For this tutorial, I'm going to start with the Responsive Mobile First CSS Skeleton I created for this website. This code works in all major browsers, and the breakpoints cover the most popular screen sizes.

The most important thing to remember is to design for mobile first, then work up to desktop sizes. This allows the mobile content to be delivered first and optimised for mobile. Larger devices will have more resources and be able to handle larger content so they can load them in when needed. A good example is photography - a mobile device may struggle loading in an image 2000x2000 pixels, so we use a smaller size, say 800x800. That is the base size. Now, as screen size increases, we can load up larger images, overriding the previous breakpoint settings. This is good for typography as well, we can use small fonts on small screens, and larger fonts on larger screens, keeping proportions correct.

CSS3 Media Queries Breakpoints

So let's have a look at the base CSS and the breakpoints. I've added a selector for the body:after, this will allow us to easily see which breakpoint we are looking at when testing, however, this should be removed before transferring to a live production system.

Example of Responsive Web Design
Setting different breakpoints using CSS3 media queries allows different views depending on screen size
css
/* Common base styles for all devices */
body:after { content: 'Size: Mobile below 480px';background:yellow;padding:0.25em}

@media only screen and (min-width: 480px) {
  /* Styles for wide mobiles (480px) and above */
  body:after { content: 'Size: Wide mobile 480px and up'; }
}

@media only screen and (min-width: 768px) { 
  /* Styles for tablets/netbooks (768px) and up */
  body:after { content: 'Size: Tablets 768px and up'; }
}

@media only screen and (min-width: 1024px) { 
  /* Styles for large screens (desktops 1024px) and above */
  body:after { content: 'Size: Desktop 1024 and up'; }
}

  View Example on CodePen 

From this, we can see the common styles for all sizes at the top. This section will contain the vast majority of your styles, but only for mobile devices. You can set all your font stacks, typography, margins, padding and borders etc here. The first section of the CSS targets screens less than 479 pixels wide. Typically this will be mobile phones in portrait orientation.

Each of the breakpoints defines a "best guess" for device sizes. The next section covers screen sizes between 480 and 767 pixels. Typically this will be mobile phones in landscape orientation.

The next section covers 768 to 1023 pixels and will most commonly be tablets, high-end mobiles, or phablets.

The final section covers everything above 1024 pixels, so that would be laptops, desktops and maybe some high-end tablets.

In Bootstrap, these sections are called base (or sometimes XS), SM, MD, LG. You can create CSS selectors to target specific rules for each screen size. We'll have a look at these later on in the article.

Responsive Typography using CSS3 Media Queries

Let's first have a look at how we can use these breakpoints to create responsive typography. It's a lot easier than you think!

The first thing we are going to do is set the base font size. To do this we are going to set a fixed font size on the body, then the other elements will use a value relative to this using the EM units.

css
/* Common base styles for all devices */
body {
  font-size: 14px;
  line-height: 1.57em;
  font-family: georgia
}

body:after {
  content: 'Size: Mobile below 480px';
  background: yellow;
  padding: 0.25em
}

h1 {
  font-size: 2em
}

h2 {
  font-size: 1.5em
}

h3 {
  font-size: 1.25em
}

h4, p {
  font-size: 1em
}

@media only screen and (min-width: 480px) {
  /* Styles for wide mobiles (480px) and above */
  body:after {
    content: 'Size: Wide mobile 480px and up';
  }
}

@media only screen and (min-width: 768px) {
  /* Styles for tablets/netbooks (768px) and up */
  body {
    font-size: 16px
  }
  body:after {
    content: 'Size: Tablets 768px and up';
  }
}

@media only screen and (min-width: 1024px) {
  /* Styles for large screens (desktops 1024px) and above */
  body {
    font-size: 20px
  }
  body:after {
    content: 'Size: Desktop 1024 and up';
  }
}

From here you can see in the common block we set the base body font size to 14px, all the other sizes are measured in EM's. 1 em is equal to the base font size, 2em is equal to double the font size, and you can use any value in between. To change the font-size across all the screen sizes, making the text larger and easier to read on larger screens is simply a matter of increasing the base font size.

Responsive Images with CSS3 Media Queries

There are several ways of doing responsive images, but I've found that the most effective is to set the max-width to 100% and the height to auto. This allows the image to scale nicely at smaller sizes.

css
.img-responsive {
  max-width:100%;
  height:auto;
}

This rule does not need to be overridden in the larger screen sizes, but it is still handy to include.

Showing Content or Hiding Content with CSS3 Media Queries

Sometimes it is a requirement that certain content should not be shown on mobile, or visible only on mobile. In this case, we can again use CSS3 media queries. This code example is based on the Bootstrap framework, simplified for this demonstration.

We can use a set of classes to hide elements, we'll call this hidden-X, where X is going to be the screen size. We can also use a set of classes called visible-X where X is again the screen size.

The principle is that the hidden classes can be applied to classes which should be hidden at the specified size and below, while the visible classes work the other way around. In Bootstrap, the sizes are defined as XS (our base), SM (wide mobile), MD (tablet), and LG (desktop). These are the class conventions that are used in Bootstrap and have become an unofficial standard.

css
.hidden-xs, .visible-sm, .visible-md, .visible-lg {visibility:hidden;display:none}

This code is going to set the hidden class of the base size to hidden, and also the visible classes for larger sizes all to hidden. That means that anything tagged with the visible-md class will not be shown until the screen size is a tablet or larger.

We can add other classes at each of the breakpoints so that elements can become visible or made hidden.

css
/* Common base styles for all devices */
.hidden-xs,
.visible-sm,
.visible-md,
.visible-lg {
  visibility: hidden;
  display: none
}

@media only screen and (min-width: 480px) {
  /* Styles for wide mobiles (480px) and above */
  .hidden-sm {
    visibility: hidden;
    display: none
  }
  .visible-sm {
    visibility: visible;
    display: block
  }
}

@media only screen and (min-width: 768px) {
  /* Styles for tablets/netbooks (768px) and up */
  .hidden-md {
    visibility: hidden;
    display: none
  }
  .visible-md {
    visibility: visible;
    display: block
  }
}

@media only screen and (min-width: 1024px) {
  /* Styles for large screens (desktops 1024px) and above */
  .hidden-lg {
    visibility: hidden;
    display: none
  }
  .visible-lg {
    visibility: visible;
    display: block
  }
}

Within the media query sections, you can add any valid CSS rules and selectors as you normally would, at the end of the day the sky is the limit as to what you can do.

Responsive Grid Layouts with CSS3 Media Queries

Responsive grid layouts are usually based on a 12-column layout and have multiple tiers, one for each media query range. Bootstrap, for example, defines a series of column classes which are used inside containers and rows and allow layouts to change based on screen resolution. Each column class defines a certain width percentage and the breakpoint at which it is applied. Below this breakpoint, either a smaller size is applied or if none, the default of 100% is used. Column classes use the same XS, SM, MD, LG notation as the visible and hidden classes above.

The 12-column grid defines column names with these rules - col (indicating column), MD (size) and the number of columns to span. For example, col-md-4 is a column, at the medium size will be 33% available width. Below medium size, it will be 100% width. The number in a row must add up to 12 and you can have any combinations.

Within the media query sections, you can add any valid CSS rules and selectors as you normally would, at the end of the day the sky is the limit as to what you can do.

col-XX-1 col-XX-1 col-XX-1 col-XX-1 col-XX-1 col-XX-1 col-XX-1 col-XX-1 col-XX-1 col-XX-1 col-XX-1 col-XX-1
col-XX-4 col-XX-4 col-XX-4
col-XX-4 col-XX-8
col-XX-6 col-XX-6
col-XX-12

You can also specify that a column has different widths at different screen sizes. For example, you could have class="col-sm-6 col-md-4 col-lg-3" which would make the element 100% width below small size, at small size it will be half width (12 / 2 = 6), at medium size it will be 33% width (12 / 3 = 4) and at large size it will be 25% in width (12 / 4 = 3).

Using these column classes you can create web page layouts which adapt to the available screen size. Typically websites have a two or three-column layout - a left sidebar, the content column and a right sidebar. On mobile devices, the sidebars are less important than the content, so moving them underneath the content frees up space for the content. Using a responsive layout you can bring the content to the top of the page, and the two sidebars will be shown underneath the content.

xml
<div class="container">
    <div class="row">
        <div class="col-sm-3 col-md-2"><!--Column one--></div>
        <div class="col-sm-9 col-md-8"><!--Column two--></div>
        <div class="col-sm-12 col-md-2"><!--Column three--></div>
    </div>
</div>

Minimal Responsive Mobile First CSS Skeleton Template

A minimal, no-nonsense, responsive, mobile-first CSS3 skeleton template which demonstrates CSS3 media queries for varying screen sizes. No frameworks, no JavaScript just the absolute bare bones.

When developing the responsive mobile-first CSS for this website, I had a look around Google for decent CSS3 media query examples, but I really wanted something that isn't part of a framework with typography, grids, javascript, CSS resets and so on built-in. All I wanted was a simple, minimal, barebones media query example. Even the barebones  and skeleton  frameworks are several kb in size and stripped of all their resets still didn't give me the fluid responsive mobile-first CSS template example I needed.

With that in mind, I created this minimal responsive template which shows nothing but mobile-first CSS3 media queries and how the style for the smallest width is used for larger widths. Best of all it works in all major browsers!

You can see how the different CSS3 media queries affect the responsive template by resizing your browser window and see how the layout changes based on the width. The common base styles are applied to every browser style, but those within min-width:480px style block are only applied to browser sizes of 480px and up. Style definitions in this block will override those in the common area, the same is true for the other CSS3 media queries until the desktop size overrides the tablet, mobile and common.

This code works in all major browsers, apart from Internet Explorer 8 and below. To fix that you need to use a section of JavaScript called css3-mediaqueries-js . This script converts the CSS3 media queries into a format supported by IE8.

Responsive Mobile First CSS Template

xml
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title></title>
  <style type="text/css">
    /* Common base styles for all devices */
    .allWidths {font-size:1.5em}
    body:after { content: 'Size: Mobile below 480px';background:yellow;padding:0.25em}

    @media only screen and (min-width: 480px) {
      /* Styles for wide mobiles (480px) and above */
      body:after { content: 'Size: Wide mobile 480px and up'; }
      .wideMobileOnly {font-size:1.5em;color:pink}
    }

    @media only screen and (min-width: 768px) { 
      /* Styles for tablets/netbooks (768px) and up */
      body:after { content: 'Size: Tablets 768px and up'; }
      .tabletOnly {font-size:1.5em;color:blue}
    }

    @media only screen and (min-width: 1024px) { 
      /* Styles for large screens (desktops 1024px) and above */
      body:after { content: 'Size: Desktop 1024 and up'; }
      .desktopOnly {font-size:1.5em;color:green}
    }
  </style>
</head>
<body>
  <p class="allWidths">Styled on All Device Sizes


  <p class="wideMobileOnly">Styled on Wide Mobiles and Up


  <p class="tabletOnly">Styled on Tablets and Up


  <p class="desktopOnly">Styled on Desktop Only


  Resize browser to see how styles change according to browser width.


</body>
</html>
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

We respect your privacy, and will not make your email public. Learn how your comment data is processed.