Providing a mobile version with CSS Media Queries

Vincent Bernat

Nowa­days, many web­sites pro­vide a mo­bile ver­sion, like Wikipedia, which usu­ally is a ver­sion tai­lored to de­vices with less band­width and smaller screen. CSS Me­dia Queries is a can­di­date rec­om­men­da­tion from the W3C to sup­port dif­fer­ent stylesheets de­pend­ing on how the doc­u­ment is dis­played. This al­lows you to build a mo­bile ver­sion just by pro­vid­ing ad­di­tional in­struc­tions in your CSS style sheet.

Using CSS Media Queries#

There are two ways to use CSS me­dia queries. You can pro­vide an ad­di­tional 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 view­port is less than 700 pix­els, the stylesheet mobile.​css will be used. An­other way to use CSS me­dia queries is to de­clare a sec­tion in­side your cur­rent CSS style sheet:

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

While there are many avail­able prop­er­ties, the two most com­mon ones will be max-width and min-width. You can use this fea­ture to mod­ify some as­pects of your web site like re­duc­ing mar­gins or hid­ing some ex­tra nav­i­ga­tional blocks.

Browser support#

Cur­rent ver­sions of mo­bile browsers sup­port CSS me­dia queries: Sa­fari Mo­bile, An­droid browser and Opera mo­bile will han­dle it with­out a glitch. If you use CSS me­dia queries to pro­vide a mo­bile ver­sion of your web site, you do not re­ally have to worry about browser com­pat­ibility.

There ex­ists poly­fills that will en­able this fea­ture on un­sup­ported browsers like In­ter­net Ex­plorer 8. One of them is Re­spond which is a light­weight poly­fill tar­geted at sup­port­ing only min-width and max-width in In­ter­net Ex­plorer 6, 7 and 8.

Example#

I have added CSS me­dia queries to my web­site. Try it by re­siz­ing the win­dow of your browser. Here are some of the changes de­pend­ing on the width of the window:

  • the side­bar trans­forms into a topbar
  • the search box is hidden
  • pad­ding is re­duced at var­i­ous places

Here is the cur­rent look in a clas­sic browser:

Website look on a classic browser
Desktop view

If you re­duce the size of your win­dow, you will get some­thing like this:

Website look on a narrow window
Mobile view

Browse my CSS files for more ex­am­ples. Look at the end of each file. For fur­ther in­for­ma­tion, have a look at the ar­ti­cle from CSS Tricks.