Create an adaptable website layout with CSS3 media queries

by Jean. 21 Comments -

With the rise of both very large screens and mobile devices, web developers have to be able to create websites that display correctly and look good whatever the device is. Sure, you can use good old techniques like fluid layouts, but I’ve got something better to show you today. This tutorial will teach you how you can create an adaptable website layout using CSS3.

Getting started

Creating the default layout

The first step of this tutorial is obviously to create a HTML page. I chose to make a simple HTML5 page with only a header image, a title, and some text. Copy the following code and paste it into a file named index.html.

<!DOCTYPE html>
<html lang="en">
 
<head>
	<meta charset="utf-8">
   	<title>Cats Who Code demo</title>
	<link href="style.css" type="text/css" rel="stylesheet" media="screen">
	<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
</head>
 
 
<body>
	<div id="container">
		<header class="ma-class-en-css">
			<h1 id ="logo"><a href="#">Cats Who Code</a></h1>
		</header>
        
		<div id="content">
       		<h2>Paris, France</h2>
        	<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a ligula massa. Donec consequat, risus nec viverra condimentum, elit velit dignissim dui, id congue sapien leo tincidunt est. Mauris consectetur tempus lorem id aliquet. Proin eu faucibus massa. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In magna ligula, ornare sed posuere faucibus, consequat ac lacus. Fusce sodales fermentum nibh, a imperdiet nisi bibendum eget. Donec gravida iaculis sapien eu consectetur. Curabitur id augue augue. Nam mauris urna, suscipit eget faucibus sit amet, mollis vitae felis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris ipsum lectus, imperdiet id aliquam nec, vulputate vitae mauris. Integer gravida, neque eu placerat egestas, urna metus bibendum nisl, quis congue felis velit id diam. Quisque non tortor at turpis facilisis placerat quis sed felis. Ut eget ipsum dolor, id lacinia leo. Vivamus vitae blandit libero. Integer ultricies gravida leo quis lobortis. Morbi ultrices risus vulputate magna dignissim sed ultricies arcu tristique. Sed non facilisis sapien.</p>

			<p>Integer faucibus, augue vitae vulputate sodales, tellus tellus vulputate tortor, in iaculis ipsum orci vitae libero. Vestibulum laoreet accumsan erat vel pretium. Ut turpis elit, ultricies id accumsan non, condimentum feugiat neque. Nam ut erat urna, a porta augue. Donec vel porttitor magna. Cras eget tortor eget ante malesuada sodales sed a leo. Fusce sit amet cursus sem. Nulla aliquet accumsan ante sit amet condimentum. Morbi varius porta sapien nec iaculis. In gravida velit at nulla imperdiet varius.</p>
        </div><!-- #content -->

		<footer>A demo by <a href="http://www.catswhocode.com">CatsWhoCode</a></footer>
	</div><!-- #container -->
</body>
</html>

Once done, we have to add a stylesheet to our index.html page. The following code is the basic styling for the page. Paste it into a file named style.css.

*{
	/* On a production site, use a real reset instead of this! */
	margin:0;
	padding:0;  
}            
    
body{
	background:#f5f5f5;
	font-family:"Lucida Grande", Arial;
	font-size:13px;
	line-height:21px;
	color:#444;  
}     

p{
	margin:15px 0;
}              

h2{
	margin-top:20px;
}

#container{
	background:#fff;
	border-left:1px #ddd solid;
	border-right:1px #ddd solid;
	border-bottom:1px #ddd solid;
	width:600px;
	margin:0 auto;
}  

header h1#logo a{
	text-indent:-9999px;
	display:block;
	width:600px;
	height:82px;
	background:url(image-med.jpg) no-repeat 0 0;
}             

#content{
	width:95%;
	margin:0 auto;
}

footer{
	text-align:center;
	width:100%;
	display:block;    
	font-size:11px;
}                            

Right now, if you look to your index.html page through your web browser, you’ll see something like the screenshot below. Nothing spectular, right? Keep reading, we’re going to dive into the interesting part.

Using CSS3 media queries to make our layout fit in all screen resolutions

If you had a look to your index.html page with a screen resolution bigger than 800*600, you might find the layout is really small. So, what about allowing large screens to display a bigger version, while still using the small version for people with lower resolutions?

This is what CSS3 media queries can do for you. Open your style.css file and paste the code below at the end of the file:

@media screen and (min-width:1200px){
	#container{
		width:1100px;
	}  
	
	header h1#logo a{
		width:1100px;
		height:150px;
		background:url(image.jpg) no-repeat 0 0;
	}                          
	
}

Now, have a look at index.html again: The layout is indeed bigger. Horizontally resize the window size… The site switches back to the small layout. How great is that?

As you can see, there’s nothing complicated at all in implementing this technique. @media screen tells the browser this applies only for screens, because we don’t want to resize anything for print. And and (min-width:1200px) specifies that the screen must have a 1200px minimum width. If these requirements are met, then the code within the parenthesis is taken into consideration by the browser, and redefines previous styles.

Now that we created a bigger version for bigger screens, what about a very small version for mobiles? Paste this code into style.css and you’re done.

@media screen and (max-width:767px){
	#container{
		width:320px;
	} 
	
	header h1#logo a{
		width:320px;
		height:44px;
		background:url(image-small.jpg) no-repeat 0 0;
	}                           
	
}

Dealing with images

Images always play an important part of a website. So, let’s add an image to our website layout. Re-open index.html and insert the following code just before the first closing </p>

<img src="notre-dame.jpg" alt="Photo by Wlappe">

If you have a look to index.html with a big screen, no problem. But if you resize the window horizontally…ouch.

The solution to that problem is quite simple: As we resize the website layout, we have to resize images as well. The max-width CSS property is here to help.

Insert the following on your style.css file:

img {
	max-width:570px;
	margin:10px 0;
}

A default image size is now defined. Now we can setup sizes for big screens as well as mobile devices:

@media screen and (min-width:1200px){
	img {
		max-width:1000px;
	}
}

@media screen and (max-width:767px){  
	img {
    	max-width:305px;
	} 
}

Now, resize your browser: Images are resized with the layout!

Limitations

Guess what? Internet Explorer (excepted the newly released IE9) doesn’t know anything about the CSS @media property. Which means that even on a big screen, IE users will see the default layout.

Hope you enjoyed this tutorial. Have a great day!

  • http://welcomebrand.co.uk James

    Good primer on responsive layouts, maybe consider using max-width:100% on images though, it should offer a little more flexibility :)

    http://unstoppablerobotninja.com/entry/fluid-images/

    J.

  • http://www.barreverte.fr JP

    Hi,

    I wondered when I read that :
    /* On a production site, use a real reset instead of this! */

    how do you do a real reset ?

    thanks

    • http://www.wprecipes.com Jean-Baptiste Jung

      The “*” reset is not really good, I inclued it only because the file was an example. A great reset is this one: http://html5doctor.com/html-5-reset-stylesheet/

      Cheers!

      • http://www.barreverte.fr JP

        Ah ok ! merci…
        (I found the original Eric Meyer css reset in my bookmarks, under 30cm of dust)

  • http://www.forwardmediagroup.com Jeff Friend

    Excellent basic tutorial on adaptable website layouts! Thanks.

  • http://www.veepiz.com jordah

    Thanx for giving me an insight on media queries…. always thot it was very complicated.. but from the way things look, i can now tame css. cheers

  • http://iequalszero.com Jon Howard

    Good article. I have a few sites queued up for a mobile revamp. It’ll be interesting to apply these techniques to sites with more complicated layouts.

  • Pablo Mendoza

    Hi, there is a polyfill for media queries in IE 6-8: https://github.com/scottjehl/Respond

    • http://www.wprecipes.com Jean-Baptiste Jung

      Very interesting, thanks!

    • http://gregbabula.info Greg Babula

      Thanks for this!

      Great article

  • http://www.olivermichas.com Identity

    Very nice article, I was wondering for a while how to achieve this ^^ Finally got my answer !

    I have another question though: Is it possible to have a separate css file using this technique (for big websites for example).
    I was thinking of something like a css include ?

    Thanks again !

    • http://www.wprecipes.com Jean-Baptiste Jung

      Sure! For example:
      <link rel=”stylesheet” media=”screen and (max-width: 640px)” href=”smallscreen.css” type=”text/css” />

  • http://www.cedricjans.com Ced

    Bien Jouer!!! :D this will definitively help!! will use it immidiately. Have been looking for something like this for ages and ofcourse the old versions of IE won’t work, it’s like you don’t even have to say it and everybody would have guessed it :P lol

  • http://www.techzil.com Sharat

    Excellent work. I was searching for it.

    Thanks :) ..

  • http://accesisbleweb.eu Richard

    The good news though is that this can be made to work in pre 9 versions of IE with https://github.com/scottjehl/Respond

  • http://www.facebook.com/pages/Luca-Cavallotto/250315134995852 Luca Cavallotto

    Cool! Just wondering to know what about the browser compatibility. I mean, ok IE sucks, but what about the other browser versions?

  • http://www.facebook.com/pages/Luca-Cavallotto/250315134995852 Luca Cavallotto

    Nice tutorial and nice tips. Maybe using percentage for the width of the images, logo images and so on would be better… Don’t you think? Anyway, great tutorial

  • http://faceleakz.blogspot.com FL

    Yes it works on my blog.

  • RoberRM

    Great tutorial: simple and yet very well explained. Thank you for your teachings. :)

  • http://www.toscano.com.br Marcelo Toscano

    Just to let you know, but your demo http://www.catswhocode.com/demos/css3-media-queries/ is reaching a 4040 page …

  • http://www.homertechnologies.ca Maurine

    Simple and best tutorial to start with responsive web design. for browsers <ie9 you can add a tip about html5.js

    thanks