Menu Search
Jump to the content X X
Smashing Conf Barcelona 2016

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

How To Use CSS3 Media Queries To Create a Mobile Version of Your Website

CSS3 continues to both excite and frustrate web designers and developers1. We are excited about the possibilities that CSS3 brings, and the problems it will solve, but also frustrated by the lack of support in Internet Explorer 8. This article will demonstrate a technique that uses part of CSS3 that is also unsupported by Internet Explorer 8. However, it doesn’t matter as one of the most useful places for this module is somewhere that does have a lot of support — small devices such as the iPhone, and Android devices.

In this article I’ll explain how, with a few CSS rules, you can create an iPhone version of your site using CSS3, that will work now. We’ll have a look at a very simple example and I’ll also discuss the process of adding a small screen device stylesheet to my own site to show how easily we can add stylesheets for mobile devices to existing websites.

Media Queries Link

If you have ever created a print stylesheet for a website then you will be familiar with the idea of creating a specific stylesheet to come into play under certain conditions – in the case of a print stylesheet when the page is printed. This functionality was enabled in CSS2 by media types. Media Types let you specify a type of media to target, so you could target print, handheld and so on. Unfortunately these media types never gained a lot of support by devices and, other than the print media type, you will rarely see them in use.

The Media Queries2 in CSS3 take this idea and extend it. Rather than looking for a type of device they look at the capability of the device, and you can use them to check for all kinds of things. For example:

  • width and height (of the browser window)
  • device width and height
  • orientation – for example is a phone in landscape or portrait mode?
  • resolution

If the user has a browser that supports media queries then we can write CSS specifically for certain situations3. For example, detecting that the user has a small device like a smart phone of some description and giving them a specific layout. To see an example of this in practice, the UK web conference dConstruct4 has just launched their website for the 2010 conference and this uses media queries to great effect.

dConstruct 2010 website on a desktop browser5
The dConstruct 2010 website in Safari on a desktop computer

dconstruct website on the iPhone6
The dConstruct 2010 website on an iPhone

You can see from the above example that the site hasn’t just been made smaller to fit, but that the content has actually been re-architected to be made more easy to access on the small screen of the device. In addition many people might think of this as being an iPhone layout – but it isn’t. It displays in the same way on Opera Mini on my Android based phone – so by using media queries and targeting the device capabilities the dConstruct site caters for all sorts of devices – even ones they might not have thought of!

Using Media Queries to create a stylesheet for phones Link

To get started we can take a look at a very simple example. The below layout is a very simple two column layout.

Simple example in a browser7
A very simple two column layout

To make it easier to read on a phone I have decided to linearize the entire design making it all one column, and also to make the header area much smaller so readers don’t need to scroll past the header before getting to any content.

The first way to use media queries is to have the alternate section of CSS right inside your single stylesheet. So to target small devices we can use the following syntax:

@media only screen and (max-device-width: 480px) {

	}

We can then add our alternate CSS for small screen and width devices inside the curly braces. By using the cascade we can simply overwrite any styles rules we set for desktop browsers earlier in our CSS. As long as this section comes last in your CSS it will overwrite the previous rules. So, to linearize our layout and use a smaller header graphic I can add the following:

@media only screen and (max-device-width: 480px) {
		div#wrapper {
			width: 400px;
		}

		div#header {
			background-image: url(media-queries-phone.jpg);
			height: 93px;
			position: relative;
		}

		div#header h1 {
			font-size: 140%;
		}

		#content {
			float: none;
			width: 100%;
		}

		#navigation {
			float:none;
			width: auto;
		}
	}

In the code above I am using an alternate background image and reducing the height of the header, then setting the content and navigation to float none and overwriting the width set earlier in the stylesheet. These rules only come into play on a small screen device.

Simple example on a phone8
My simple example as displayed on an iPhone

Linking a separate stylesheet using media queries Link

Adding the specific code for devices inline might be a good way to use media queries if you only need to make a few changes, however if your stylesheet contains a lot of overwriting or you want to completely separate the styles shown to desktop browsers and those used for small screen devices, then linking in a different stylesheet will enable you to keep the CSS separate.

To add a separate stylesheet after your main stylesheet and use the cascade to overwrite the rules, use the following.

<link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="small-device.css" />

Testing media queries Link

If you are the owner of an iPhone, Android device or other device that has a browser which supports media queries you can test your CSS yourself. However you will need to upload the code somewhere in order to view it. What about testing devices you don’t own and testing locally?

An excellent site that can help you during the development process is ProtoFluid9. This application gives you a form to enter your URL – which can be a local URL – and view the design as if in the browser on an iPhone, iPad or a range of other devices. The screenshot below is the dConstruct site we looked at earlier as seen through the iPhone view on ProtoFluid.

dConstruct site in ProtoFluid10
The dConstruct 2010 website in ProtoFluid

You can also enter in your own window size if you have a specific device you want to test for and know the dimensions of it’s screen.

To use ProtoFluid you need to slightly modify the media query shown earlier to include max-width as well as max-device-width. This means that the media query also comes into play if the user has a normal desktop browser but using a very tiny window.

@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {

	}

After updating your code to the above, just refresh your page in the browser and then drag the window in and you should see the layout change as it hits 480 pixels. The media queries are now reacting when the viewport width hits the value you entered.

You are now all ready to test using ProtoFluid. The real beauty of ProtoFluid is that you can still use tools such as FireBug to tweak your design, something you won’t have once on the iPhone. Obviously you should still try and get a look at your layout in as many devices as possible, but ProtoFluid makes development and testing much simpler.

Note that if you don’t want your site to switch layout when someone drags their window narrow you can always remove the max-width part of the query before going live, so the effect only happens for people with a small device and not just a small browser window.

Retrofitting an existing site Link

I have kept the example above very simple in order to demonstrate the technique. However this technique could very easily be used to retrofit an existing site with a version for small screen devices. One of the big selling points of using CSS for layout was this ability to provide alternate versions of our design. As an experiment I decided to take my own business website and apply these techniques to the layout.

The desktop layout Link

The website for my business currently has a multi-column layout. The homepage is a little different but in general we have a fixed width 3 column layout. This design is a couple of years old so we didn’t consider media queries when building it.

edgeofmyseat.com website in Safari on the desktop11
My site in a desktop browser

Adding the new stylesheet Link

There will be a number of changes that I need to make to linearize this layout so I’m going to add a separate stylesheet using media queries to load this stylesheet after the current stylesheet and only if the max-width is less than 480 pixels.

<link rel="stylesheet" type="text/css" media="only screen and (max-width: 480px), only screen and (max-device-width: 480px)" href="/assets/css/small-device.css" />

To create my new stylesheet I take the default stylesheet for the site and save it as small-device.css. So this starts life as a copy of my main stylesheet. What I am going to do is go through and overwrite certain rules and then delete anything I don’t need.

Shrinking the header Link

The first thing I want to do is make the logo fit nicely on screen for small devices. As the logo is a background image this is easy to do as I can load a different logo in this stylesheet. I also have a different background image with a shorter top area over which the logo sits.

body {
		background-image: url(/img/small-bg.png);
	}

	#wrapper {
		width: auto;
		margin: auto;
		text-align: left;
		background-image: url(/img/small-logo.png);
		background-position: left 5px;
		background-repeat: no-repeat;
		min-height: 400px;
	}

Linearizing the layout Link

The next main job is to linearize the layout and make it all one column. The desktop layout is created using floats so all I need to do is find the rules that float the columns, set them to float: none and width:auto. This drops all the columns one under another.

.article #aside {
		float: none;
		width: auto;
	}

Tidying up Link

Everything after this point is really just a case of looking at the layout in ProtoFluid and tweaking it to give sensible amounts of margin and padding to areas that now are stacked rather than in columns. Being able to use Firebug12 in ProtoFluid makes this job much easier as my workflow mainly involves playing around using Firebug until I am happy with the effect and then copying that CSS into the stylesheet.

The mobile layout on ProtoFluid13
Testing the site using ProtoFluid

Testing in an iPhone Link

Having created my stylesheet and uploading it I wanted to check how it worked in a real target device. In the iPhone I discovered that the site still loaded zoomed out rather than zooming in on my nice readable single column. A quick search on the Safari developer website14 gave me my answer – to add a meta tag to the head of the website setting the width of the viewport to the device width.

<meta name="viewport" content="width=device-width" />

After adding the meta tag the site now displays zoomed in one the single column.

edgeofmyseat.com on the iPhone15
The site as it now displays on an iPhone

This was a very simple retrofit to show that it is possible to add a mobile version of your site simply. If I was building a site from scratch that I would be using media queries on, there are definitely certain choices I would make to make the process simpler. For example considering the linearized column orders, using background images where possible as these can be switched using CSS – or perhaps using fluid images16.

Our desktop layout features a case studies carousel on the homepage, this wasn’t easy to interact with on a touch screen device and so I checked using JavaScript if the browser window was very narrow and didn’t launch the carousel. The way this was already written meant that the effect of stopping the carousel loading was that one case study would appear on the screen, which seems a reasonable solution for people on a small device. With a bit more time I could rewrite that carousel with an alternate version for users of mobile devices, perhaps with interactions more suitable to a touch screen.

More resources Link

This is a relatively new technique but already there are some excellent tutorials on the subject of media queries. If you know of others then please post them in the comments.

Providing support for Media Queries in older browsers Link

This article covers the use of media queries in devices that have native support. If you are only interested in supporting iPhone and commonly used mobile browsers such as Opera Mini you have the luxury of not needing to worry about non-supporting browsers. If you want to start using media queries in desktop browsers then you might be interested to discover that there are a couple of techniques available which use JavaScript to add support to browsers such as Internet Explorer 8 (and lower versions) and Firefox prior to 3.5. Internet Explorer 9 will have support for CSS3 Media Queries.

More inspiration Link

To see more interesting use of Media Queries have a look at Hicksdesign26 where Jon Hicks has used Media Queries to not only provide a better experience for mobile device users, but also for regular web browser users with smaller windows. Also, have a look at Simon Collison’s website27 and Ed Merritt’s portfolio28 for other examples of this technique.

Try it for yourself Link

Using Media Queries is one place you can really start to use CSS3 in your daily work. It is worth remembering that the browsers that support media queries also support lots of other CSS3 properties so your stylesheets that target these devices can also use other CSS3 to create a slick effect when viewed on an iPhone or other mobile device. If you have implemented media queries on your site, or try this technique after reading this article, let us know in the comments.

Footnotes Link

  1. 1 https://www.smashingmagazine.com/learning-css3-useful-reference-guide/
  2. 2 http://www.w3.org/TR/css3-mediaqueries/
  3. 3 https://www.smashingmagazine.com/2011/01/guidelines-for-responsive-web-design/
  4. 4 http://2010.dconstruct.org/
  5. 5 https://www.smashingmagazine.com/wp-content/uploads/2010/06/dconstruct-desktop-crop.jpg
  6. 6 https://www.smashingmagazine.com/wp-content/uploads/2010/06/dconstruct-iphone.jpg
  7. 7 https://www.smashingmagazine.com/wp-content/uploads/2010/06/example-browser-crop.jpg
  8. 8 https://www.smashingmagazine.com/wp-content/uploads/2010/06/example-phone.jpg
  9. 9 http://protofluid.com/
  10. 10 https://www.smashingmagazine.com/wp-content/uploads/2010/06/dconstruct-protofluid-crop.jpg
  11. 11 https://www.smashingmagazine.com/wp-content/uploads/2010/06/edgeofmyseat-browser-crop.jpg
  12. 12 http://getfirebug.com/
  13. 13 https://www.smashingmagazine.com/wp-content/uploads/2010/06/edgeofmyseat-protofluid-crop.jpg
  14. 14 http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariWebContent/Introduction/Introduction.html#//apple_ref/doc/uid/TP40002051
  15. 15 https://www.smashingmagazine.com/wp-content/uploads/2010/06/edgeofmyseat-phone.png
  16. 16 http://unstoppablerobotninja.com/entry/fluid-images
  17. 17 http://www.alistapart.com/articles/responsive-web-design/
  18. 18 http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariWebContent/Introduction/Introduction.html#//apple_ref/doc/uid/TP40002051
  19. 19 http://reference.sitepoint.com/css/mediaqueries
  20. 20 http://blog.iwalt.com/2010/06/targeting-the-iphone-4-retina-display-with-css3-media-queries.html
  21. 21 http://aralbalkan.com/3331
  22. 22 http://stuffandnonsense.co.uk/blog/about/proportional_leading_with_css3_media_queries
  23. 23 http://matthewjamestaylor.com/blog/ipad-layout-with-landscape-portrait-modes
  24. 24 http://caniuse.com/#feat=css-media
  25. 25 http://code.google.com/p/css3-mediaqueries-js/
  26. 26 http://hicksdesign.co.uk/journal/finally-a-fluid-hicksdesign
  27. 27 http://colly.com/
  28. 28 http://www.edmerritt.com/
SmashingConf Barcelona 2016

Hold on, Tiger! Thank you for reading the article. Did you know that we also publish printed books and run friendly conferences – crafted for pros like you? Like SmashingConf Barcelona, on October 25–26, with smart design patterns and front-end techniques.

↑ Back to top Tweet itShare on Facebook

Advertisement

Rachel Andrew is a web developer, writer and speaker and one of the people behind the content management system, Perch. She is the author of a number of books including The Profitable Side Project Handbook. She writes about business and technology on her own site at rachelandrew.co.uk.

  1. 1

    Peter Druska

    July 19, 2010 3:50 am

    Protofluid is useful tool. I am using @media queries and I have to say: it is great. I see IE as a device (not a browser) and code as simple CSS as I can for it (but useful for users). So for other browsers I can build nice website using CSS3.

    -9
  2. 2

    One of the best design I’ve seen using this technique is the one given at the end of the article : http://hicksdesign.co.uk/journal/finally-a-fluid-hicksdesign

    4
  3. 3

    John Slater

    July 19, 2010 4:45 am

    Another reason CSS3 is ace but another kick in the nuts when i think the most popular version of IE for the next 5 years wont support it.

    -4
    • 4

      Drew McLellan

      July 19, 2010 4:58 am

      This article is about creating a mobile version of your site – so as long as your mobile device isn’t running Internet Explorer, that’s not really a concern.

      0
  4. 5

    This is a really nice and clear article. I assume that you used the 480px width because this is the width of an iPhone.

    It would be really useful to have a table of device widths, I would use that resource a lot!

    0
  5. 10

    Question:

    What effect does the retina display and it’s higher resolution have on mobile design? Wouldn’t the resolution of the new iPhone be on par with that of small monitors due to the high ppi?

    3
  6. 11

    Tobby Smith

    July 19, 2010 6:35 am

    I really liked this article. Good read!

    4
  7. 12

    This is the first useful article on the once great Smashing Mag in weeks.

    0
  8. 13

    Dude, I’ve got a question. Didn’t you write this article just to make everyone know that you’ve got the new iPhone with retina-crazy display that displays de puta madre?

    Noo, just kidding. Keep up the good articles-writing-job!

    It’s true that we – as digital content consumers – are evolving towards being more and more >>mobile<<, which makes the demand for << mobile >> content greater every day. That’s why I find this article well invested 15 minutes!

    Cheers!

    -2
  9. 14

    Interesting article, but I’m more intereste on the Peter Druska reply.
    What kind of media queries do you do to identify IE ?

    2
    • 15

      Peter Druska

      July 19, 2010 5:30 am

      I do not identify IE using @media. I do this:
      1) build CSS for IE (and all other browsers) useful without @media,
      2) build CSS using @media queries and other CSS3 posibilities for non-ie browsers.

      Result:

      Website is build for IE browsers with all of useful parts of website. Because IE is used only on desktops/notebooks, not on mobile devices, for all other browsers are applied styles from @media queries. IE9 will be support @media queries, so … :-)

      2
      • 16

        Unless of course you are using a Windows Mobile phone running IE5 or IE6

        -1
        • 17

          Peter Druska

          July 20, 2010 9:03 pm

          Of course. How many users use IE5 or IE6 on Windows Mobile? I think Opera is default browser.

          -4
  10. 18

    Brad Czerniak

    July 19, 2010 5:58 am

    I’m using this technique to make a regular site mobile, and I’ve run into a design problem and also a solution that may be useful for those doing the same.

    First, the problem: tables. If you use good, semantic data tables on your site and cannot control the number of columns or their width, it’s difficult to create a way to display them that doesn’t sometimes create a horizontal-scrolling situation. A big advantage of no-scale viewport layouts is that the user can vertical scroll without accidentally horizontal scrolling. Tables ruin all of this, even when used appropriately for tabular data.

    I’ve been playing with a generalized solution but it is by no means complete. You can scope out the CSS here and play with it (sort of) in action at the site.

    Second, a solution: scripts. If you want both your styles and your behaviors to change based on a media query, you need to determine the load state as well as listen for change events if your query is based on things like width, etc. that may change.

    At the same time, you don’t want IE8- to do stuff when you resize the window, because the scripts may or may not apply in that circumstance.

    An easy way to test for media query support is to make a query that will be true all the time, like:
    @media screen and (max-width:7000px){#hours thead{width:5px;}}
    This element is always display:none; with an otherwise-declared width of 3px. So, in your JavaScript you can just test the element for its width to determine whether or not CSS Media Queries are supported.
    if($(window).width() <= 640 && $("#hours thead").css("width") == "5px"){}

    Word of caution: there may come a time when screen widths commonly become greater than 7000px. Don’t forget to move the goalposts!

    If anyone has a usable, attractive solution for displaying data tables in tiny layouts, please let me know! Thanks!

    -1
    • 19

      For your table, why not use CSS3 text rotation to get the header cells vertical then use a fixed-width cell for the content? I played around a little with this at home and managed to get it looking pretty decent. It requires some fiddly CSS [using the adjacent (+) selector] to get the positioning right, but it works. Even if your content cells were 16px wide (just enough to fit those icons), you could get a dozen columns and have enough room (more than 150px) left over to have row headers as well.

      0
      • 20

        Brad Czerniak

        July 23, 2010 5:35 am

        Ben,

        Thanks for the idea of using rotation – I’ll have to look into that.

        The table solution isn’t just for tables with icons: it would have to support text blocks and content of any width. The comfortable, legible column count would go down quite a bit if all those columns had text in them. That’s why I’m playing with non-table positioning and color cues.

        0
  11. 21

    Bobby Adamson

    July 19, 2010 6:11 am

    Way stoked on this! Thanks a lot I’m going to be playing around with this quite a bit!

    1
  12. 22

    Leslie Mathis

    July 19, 2010 7:57 am

    Great article,

    Can you suggest a site with information on displaying video clips on mobile devices which do not use flash?

    1
  13. 23

    If you have img tags in your markup, you’re going to load all of that data regardless of the whether you hide it on mobile by setting it to display:none in your media query. How do you get around this?

    4
  14. 24

    Pretty cool article.
    Most devices are 320×480 in portrait mode, high res screen are starting to appear like the iphone 4 is 640×960 and the HTC EVO is 640×800 but on a much bigger screen, same for the Motorola droid X.

    1
  15. 25

    Great article, timely too.

    Thanks for posting. BTW, I’m really enjoying these HTML5/CSS3 posts of late.

    1
    • 26

      Same here, with all the changes in CSS3 it’s nice to read something that I can use NOW. Great write up!

      1
  16. 27

    Amy Stoddard

    July 19, 2010 6:29 pm

    Up until now I’ve been using a service like Mobify.me. This to me is much more clear and I have greater control. Thanks for writing this.

    1
  17. 28

    Relying on CSS3 doesn’t make for a very accessible mobile version, doesn’t it?

    0
    • 29

      Jasper van der Kamp

      July 21, 2010 4:08 am

      Yes it does. If the browser doesn’t support media queries, it will just show the HTML. That is accessibility.
      You can btw prevent this by putting your mobile styles first in your CSS file (without media queries) and then define the wide screen styles with media queries. This way other mobile browsers (Nokia, Blackberry etc.) are also included.
      For IE<9 I use a conditional comment with the wide screen styles copied from the main stylesheet.

      1
  18. 30

    Blaze Pollard

    July 20, 2010 1:00 pm

    Ajax’d Form with Fancy Email http://bit.ly/b6GSWE

    0
  19. 31

    Love it. Just used this technique to create a mobile version of my portfolio website and am wondering what other sites I’ve made that I can apply this to. It’s actually quite easy to do, so long as you set the site up right in the first place.

    Thanks for the info.

    2
    • 32

      Love this theme! You’ll see that I’m pyialng with the custom CSS quite a bit. I am stumped though how to change the font used in the widget headings it’s some sort of all-caps right now but I’d like to modify it. I’ve been tweaking what I thought were the settings but it doesn’t seem to change. How can I do this?Also, if I wanted to modify the category results pages (i.e. when a category is selected and list of posts are returned), where would I do this? Since my content is mostly recipes, the resulting category pages don’t look very nice when returned I’d like to display the post title and thumbnail of first image in the post (possible?). It would also be nice if the category page didn’t follow the post display logic from blog settings. I’d like my blog to display the current post, but if I do the category pages will only show 1 result when selected (and then a user needs to page through the results one by one).Sorry for so many questions again, thank you for this theme!

      0
    • 33

      Some nice tips in there.One thing though: #not-iPhone isn’t a class, it’s an id meianng it can only be used once per page. I suspect you meant .not-iPhone

      0
  20. 34

    Hello,

    I’m looking for someone who could make a mobile version of my website.

    Please let me know if somebody could be interested.

    Thanks!

    0

↑ Back to top