All About CSS3 Media Queries

If I fill water in a container it will spread as per containers dimension. Media queries help us achieve similar goal. They render responsive design.

What is responsive design?

A responsive design fits itself as per the screen it is displayed on. It basically changes its design as per the screen.

All About CSS3 Media Queries

With the help of media queries, we can write CSS in such a manner that our rendered design will fit the screen it’s displayed on. Media query detects user’s browser and shows proper design made for that screen.

We normally use Media Queries to detect:

1. Width and height of the browser window
2. Device width and height
3. Orientation – for example is a phone in landscape or portrait mode

How to use Media Queries?

1. Inside the stylesheet

@media screen and (min-width: 600px) and (max-width: 900px) {
  .class {background: #333;}
}

Note: Place media queries at the end of stylesheet to override rest of the styles

2. Import from within the stylesheet

@import url("phone.css") only screen and (max-width:400px);

3. Link to the stylesheet from html file

<link rel="stylesheet" media="screen and (max-width: 600px)" href="small.css" />

Types of Media Queries

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */

Browser Support

They are normally supported by all the latest browsers – Firefox 3.5+,
Opera 9.5+, Safari 3+ (including Mobile), Chrome, Internet Explorer 9+ but lacks support for versions below IE 9+.

We have solution for IE versions that lack support

In order to fit your design in IE 8 or versions below that as per screen size we need to use JavaScript which is one of the best solutions.

We can detect the windows width and change the CSS file accordingly by using the code below. You can assign an ID for a element here.


<link rel="stylesheet" type="text/css" href="main.css" />
<link id="size-stylesheet" rel="stylesheet" type="text/css" href="narrow.css" />

Next step is to use IE specific stylesheet.

We change the href value of the stylesheet.The browser will see that code and replace the old CSS with new linked CSS.

Let’s see this in the code shown below:

function adjustStyle(width) {
    width = parseInt(width);
    if (width < 701) {
        $("#size-stylesheet").attr("href", "css/narrow.css");
    } else if ((width >= 701) && (width < 900)) {
        $("#size-stylesheet").attr("href", "css/medium.css");
    } else {
       $("#size-stylesheet").attr("href", "css/wide.css"); 
    }
}

$(function() {
    adjustStyle($(this).width());
    $(window).resize(function() {
        adjustStyle($(this).width());
    });
});

Chris Coyier wrote about how to detect browser size using jquery some time back. It’s a good article for those who are IE lovers and want everything working perfectly fine. Go check out with examples.

The article by Smashing Magazine on techniques for gracefully degrading media queries is worth reading as well.

There is one more alternative to the problem, all we need to do is leave media queries only for latest browsers and serve the older IE versions with a basic stylesheet taking help of conditional comments like in the code below:


<!--[if lt IE 9 & !IEMobile]>
<link href="iestyles.css" rel="stylesheet" type="text/css">
<![endif]-->

Read more about conditional comments.

Testing media queries

If you have an iPhone, Android device or other device that has a browser which supports media queries you can test your CSS yourself. All you need to do is upload the code and other files on server.

But what about devices you don’t own and testing needs to be performed on them?

We have a solution in form of ProtoFluid.It’s a nice website that is useful when you want to test your CSS during the development phase.

This website gives you a form to enter your URL – which can be even be a local URL – and view the design as if in the browser on an iPhone, iPad or a range of other devices.

What’s this – width, device-width, and viewport

As soon as I was ready with all the files and structure I decided to test my website in a real environment. So I just typed the Url in my iphone’s browser and discovered that it was still zoomed out and everything was very tiny. It was not readable.

Thankfully, I found the solution after some research. Came across the discovery done by Apple regarding a new tag, which has been widely adopted by various mobile devices.

The code worked nicely. Infact it has been incorporated into specification likely to be approved by the World Wide Web Consortium (W3C).

Here is our wonderful piece of code:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Just add the following line to the head section of each web page of your website.

This tells mobile devices to treat the viewport as being the same width as the physical width of the device. As a result, you can use width in media queries safe in the knowledge that it means what you think it does.

Examples

It’s best to check out now the live examples. So here is a small list which I am sharing. I would advice to test it by resizing browser window and viewing the code written for the websites. Experiment and use in your projects. It will be really interesting.

Tree House

example-treehouse

Sasquatch Festival

example-sasquatch

Converge SE

example-converge

Lapse

example-lapse

Final Words

Media queries are meant for design presentation. So take advantage and create a optimized UI for the user of your website. It will definitely leave a good impression on the user as most of them are checking and finding the information on smaller devices these days.

Reference Websites

– iPad CSS Layout with landscape / portrait orientation modes.
– Cssmediaqueries.
– CSS Media Queries & Using Available Space.
– Mozilla CSS media queries.
– Types of CSS3 Media Queries.

Do let know if I have missed on something. Do try for yourself and share the experience with us…

 

Written by Nikhil Malhotra


Hi! I am Nikhil Malhotra, a Web/UI designer and Front End developer. This is the area of my website where I share my knowledge in form of tutorials and articles.

 
This entry was posted in Code, Tutorials and tagged , , , , , . Bookmark the permalink.

6 Responses to All About CSS3 Media Queries

  1. Jitender says:

    Well written and really useful….thanks!

    • Its really nice to hear that you found the article useful:)

    • Ellie says:

      This code works great for keeping the side bar text and ieamgs in line. However, the navigation bar stacks up after the third page link. I’ve been working on this all day and am completely at a loss, as what else to try to adjust. Changing the width from 100% to a value keeps the nav bar on one line, but of course then the rest of the page gets thrown off. I’ve been restyling the CSS, mostly for #access. Is there a change that would work in the wonderful Responsive structure you have presented here? Any help would be most appreciated. Thanks!

  2. Mahima says:

    OK. I guess I was concerned that sshtelyeet_url might be used elsewhere, but there’s really no reason for that, is there? There’s also the fact that it would be nice to have some mechanism for automating the update to always use the most recent file version, but I’m just starting to expose flaws in my question now :) Aug 11 ’10 at 23:27

    • Hi Mahima,

      The best way is to integrate your media queries is in your regular stylesheet. As per my understanding the file you are referring to be updated automatically is your stylesheet. We don’t require any mechanism to update it. It’s in your hands.:)

Leave a Reply

Your email address will not be published. Required fields are marked *