Create an adaptable website layout with CSS3 media queries

Posted on May 09, 2011

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.

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:

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.