Providing a mobile version with CSS Media Queries
Vincent Bernat
Nowadays, many websites provide a mobile version, like Wikipedia[1], which usually is a version tailored to devices with less bandwidth and smaller screen. CSS Media Queries[2] is a candidate recommendation from the W3C to support different stylesheets depending on 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 know 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 two most 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[3]: 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 do not really have to worry about browser compatibility.
There exists polyfills[4] that will enable this feature on
unsupported browsers like Internet Explorer 8. One of them is
Respond[5] 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:

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

Browse my CSS files[6] for more examples. Look at the end of each file. For further information, have a look at the article from CSS Tricks[7].
- https://web.archive.org/web/2011/http://en.m.wikipedia.org
- https://www.w3.org/TR/mediaqueries-3/
- https://caniuse.com/#feat=css-media
- https://remysharp.com/2010/10/08/what-is-a-polyfill/
- https://github.com/scottjehl/Respond
- https://github.com/vincentbernat/vincent.bernat.ch/tree/bdabde61a4114fd478859502cff9f638b4beaf32/content/media/css
- https://css-tricks.com/css-media-queries/