coding guides, API's and how-to's

CSS3 Media Queries are one of the best things to happen to front-end development since that terrible blink tag was deprecated eons ago and it stopped working on MySpace backgrounds. Media queries are expressions that limit the scope of styled elements depending on media features like width and height and resolution. In other words depending on the type of output device, screen width, screen height you can render specifically targeted CSS rules to your elements.

An example would be printing a web document. Most websites don't print the entire screen when you hit CTRL-P, but instead they present you with a 'printable' version void of style, color, images and anything else that would bog down the printing process. It doesn't just apply to printing however. A more visible example would be a responsive web page whose content flows correctly in a number of different screen sizes. The web is going responsive and web standards are attempting to catch up. A few years ago you would of used a giant regex list to determine if the user was on mobile, and if they were then you would load a completely different style sheet. I know, as I've done this countless times.

Media queries solve that problem by allowing you to set expressions that determine when to use certain style sheet rules. They're simple and they can make a huge difference in usability. I recently implemented a few mobile rules to this blog which brought my mobile bounce rate down considerably. My main problem was that on mobile, this blog was showing 1 word per line :/. With a few style rules, it looks like this.

mobile layout

Much friendlier on the eyes I think.

@Media Syntax


@media mediatype and|not|only (media feature) {
    CSS-Code;
}

This is the main format for all of your media queries. It's comprised of the @media keyword followed by the media type you are targeting, logical operators and one or many media features that must evaluate to true for the style to be applied.

You also have the option of creating a separate media stylesheet, which would be ideal for large more in depth responsive projects.


<link rel="stylesheet" media="mediatype and|not|only (media feature)" href="mystylesheet.css">

With this syntax, whenever the media attribute results to true, then the stylesheet listed in the href would render.

Currently @media queries are supported by the following browser and versions.

media query browser support

Media Types

Media types are the output devices that you are targeting, like a computer screen or printer. Some time ago, there were about a dozen or so, but nowadays it's been cleaned up and we have 4 that haven't been deprecated just yet:

  • all - all devices
  • print - used for printers
  • screen - computers/laptops/tablets/smartphones
  • speech - screenreaders

For this tutorial, I will be mainly focusing on the screen media type, since that's how most people will most likely encounter it in their developer lives. The screen type represents essentially anything with a screen browsing a webpage. Phone, tablets, laptops are included in this list.


@media print
{
     body
     {
            color: orange;
     }
}

Our first media query at its most basic level. Here we are telling the browser to make all of the text orange but only if we're printing.

media print

And if we take a peek at the print preview right above, we see our results from that one little line.


Media Features

Media features are the expressions, that result to true or false that will determine if that particular media query will be active or not. In other words, what needs to happen in order for that style rule to be applied. There's a fair number of features that you can use, but as this is quick guide, I'll mainly be focusing on screen width and height in order to make more responsive web pages.

A few possible options for screen size media features are:

  • width (and max or min pre-pended)
  • height (and max or min pre-pended)
  • orientation
  • resolution

Now that we have a few more keywords to work with, let's see it in action.


        .div1 {
            background-color: #dbdbdb;
        }

        .div2 {
            background-color: #777777;
        }

        .example .rect {
            width: 45%;
            float:left;
            text-align:center;
            height: 50px;
            font-size: 30pt;
        }


<div class="example">
        <div class="div1 rect">
            DIV 1
        </div>

        <div class="div2 rect">
            DIV 2
        </div>

        <div style="clear:both"></div>
    </div>

Here we have the styles for 2 divs side by side and floating left on a 740px wide screen. As the screen width shrinks down so too will each of our divs. On smaller devices like smartphones, this isn't the most ideal layout. Believe me, I know as this blog had that same design and boy was it ugly.

media query example

So what we'll want to do is maybe have each div take up 100% space and just fall on top of each other.


@media screen and (max-width: 500px) {
            .example .rect {
                float: none;
                width: 100%;
            }
        }

We add this rule to our stylesheet and we can see that as soon as our screen width hits 500px wide, the new element styles take into effect.

media query example

The media rules cascade downwards as well. So if we wanted to target another screen size perhaps, then we can just continue to add more media queries to our style sheet.


@media screen and (max-width: 500px) {
    .example .rect {
        float: none;
        width: 100%;
     }
}

@media screen and (max-width: 450px) {
    .example .div1 {
         display: none;
    }
}

media query example

This is just a quick example to get anyone up to speed quickly with media queries. You can definitely get creative and create all kinds of responsive layouts that can fit on a plethora of screens and devices. If you minify your browser screen, you can see how blog would look on a tablet and/or smartphone and it just took a few well placed style rules to get the job done.

Walter Guevara

Walter G. is a software engineer with over 10 years of professional experience. When he isn't blogging or being a CTO he enjoys coding randomly complex things that he hopes many people will get a chance to use one day.

Comments

No comments posted yet

Latest Posts

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post comment