Providing a mobile version with CSS Media Queries

Vincent Bernat

Nowadays, many websites provide a mobile version, like Wikipedia, which usually is a version tailored to device with less bandwidth and smaller screen. CSS Media Queries is a candidate recommendation from the W3C to support different stylesheets depending on the how the document is displayed. This allows you to build a mobile version just by providing additional instructions in your CSS style sheet.

Using CSS Media Queries#

There are two ways to use CSS media queries. You can provide an additional CSS stylesheet and let the browser knows when to use it:

<link rel="stylesheet" media="screen and (max-width: 700px)" href="mobile.css">

When the width of the viewport is less than 700 pixels, the stylesheet mobile.css will be used. Another way to use CSS media queries is to declare a section inside your current CSS style sheet:

@media screen and (max-width: 700px) {
    #article {
       margin: 0.3em 0.2em;
    }
}

While there are many available properties, the most two common ones will be max-width and min-width. You can use this feature to modify some aspects of your web site like reducing margins or hiding some extra navigational blocks.

Browser support#

Current versions of mobile browsers support CSS media queries: Safari Mobile, Android browser and Opera mobile will handle it without a glitch. If you use CSS media queries to provide a mobile version of your web site, you don’t really have to worry about browser compatibility.

There exists polyfills that will enable this feature on unsupported browsers like Internet Explorer 8. One of them is Respond which is a lightweight polyfill targeted at supporting only min-width and max-width in Internet Explorer 6, 7 and 8.

Example#

I have added CSS media queries to my website. Try it by resizing the window of your browser. Here are some of the changes depending on the width of the window:

  • the sidebar transforms into a topbar
  • the search box is hidden
  • padding is reduced at various places

Here is the current look in a classic browser:

Website look on a classic browser
Desktop view

If you reduce the size of your window, you will get something like this:

Website look on a narrow window
Mobile view

Browse my CSS files for more examples. Look at the end of each file. For further information, have a look at the article from CSS Tricks.