Web Development

How to create media queries in Responsive Web Design

Ryan Boudreaux shows how to create media queries that allow the web designer to target styles based on a number of device properties, such as screen width, orientation, and resolution.

In my last post on Responsive Web Design (RWD), I introduced what RWD is, demonstrated fluid grids, and explained how to make the conversion from the traditional styling of fixed pixels and percentages to proportions using The Marcotte Calculation: Target ÷ Context = Result. Figure A at left shows a web page from Chris Coyier's CSS Tricks as displayed in a simulated iPhone test with a device screen resolution of 320x480.

Ethan Marcotte's posts on Responsive Web Design and his new book, Responsive Web Design, has spearheaded the RWD movement.

In this post, I will review how media types are evolving into media queries with RWD.

Media queries

Media queries go beyond the conventional media types that have been used since CSS 2.1, which allowed our websites to obtain some degree of media device responsiveness; for instance, see the sample external style sheet link elements using the media attribute with such references as media="screen" or media="print" below.

<link href="styles.css" type="text/css" media="screen" rel="stylesheet"/>
<link href="print.css" type="text/css" media="print" rel="stylesheet"/>

The W3C answer to improving device-specific website response is the media queries specification. Media queries open up the spectrum of possibilities with the "media" attribute that controls how the styles get applied. Media queries takes the previous scheme to the next level by allowing us to target styles based on a number of device properties, including screen width, orientation, resolution, and others. Media queries allow us to target not only certain devices and classes of devices, but it allows us to actually inspect the physical characteristics of the device.

For example, let's say we want to target iPhones, Android, and such devices which typically have a maximum screen resolution of 480px horizontal. We would establish the media query by applying two components, first setting the media type equals screen, and second, the actual query, which is enclosed in parentheses, that contains the media feature to inspect, and the target value.

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

The query above will apply this style sheet only to a device that has a screen and only if the browser window on that device has a horizontal resolution no wider than 480 pixels, otherwise the link will be ignored. You can see from the file name mobile.css that this particular query is intended for mobile device styles.

Taking this a step further, let's look at another example media query from The Goldilocks Approach to Responsive Web Design. It utilizes the following link in its example of what it calls "device independent" universal web design:

<link rel="stylesheet" href="css/example/layout.css" media="all and (min-width: 33.236em)">
<!-- 30em + (1.618em * 2) = 33.236em / Eliminates potential of horizontal scrolling in most cases -->
In the Goldilocks example above, notice that the min-width is represented in ems, and the comment to eliminate potential horizontal scrolling results from the approach that, in general, 30em usually does the trick with respect to devices that might be too small (narrow column), just right (single column), or too big (multi-column); remember "Goldilocks and the Three Bears." You can view the Goldilocks Approach Demo with the grid on or off. In Figure B, it is on.

Figure B

We can also incorporate multiple property values in media queries by chaining them together with the "and" keyword, as in the example link below:

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

Demonstrating media queries

We can also incorporate media queries in our stylesheets, so let's go back to the demonstration files (see download below) that I used in the first segment, and incorporate the media query shown below:

@media screen and (max-width:480px) {
    #blog_rwd {
      float: none;
      width: 60.714285714285714285714285714286%;
background-color:#FFB3B3;
    }
}
In this case, should the device pass the test, with a screen and maximum width of 480 pixels, it will set the #blog_rwd to a float of none and a width of 60.714285714285714285714285714286%, which is derived from Marcotte's calculation of the target width (1020px) of the element divided by the context, which is the native maximum width of the assumed container (1680px). The result is multiplied by 100 to arrive at the percentage above. Also, notice that when you resize the screen viewing area to below 480px, the background color for the blog header area will also change colors. This is for demonstration purposes to show that the media query has kicked in only when the browser maximum width has been modified, and the test is true. The resulting output as displayed in the simulated iPhone is shown in Figure C:

Figure C

Notice however, that the aside container on the left is not wrapping the text too well; to fix this, let's add in another media query to drop the aside below the article container, and then add another media query to expand the width of both containers. The two media queries are displayed below:

@media screen and (max-width:830px) {
    #blog_rwd .aside_rwd{
        float: left;
        width: 98%;
        background-color:#95C9E8;
        margin-top:5px;
    }
}
@media screen and (max-width:830px) {
    #blog_rwd .article_rwd{
        float: left;
        width: 98%;
        background-color:#B0E6C6;
        margin-top:10px;
    }
}

The original style for the article container included a float right (see code snippet below).

#blog_rwd .article_rwd {
            width: 78.431372549019607843137254901961%;
            float:right;
            padding-right:0.49019607843137254901960784313725%;
            background-color:#E3FDF8;
}

But when the browser viewable area is 830px or less, the media query will activate and the article container will float left, resize to a 98% width and the background color will change to a green hue of #B0E6C6 for the demo. This, in essence, pushes it above the aside container. The aside container will float left with a width of 98%, and the background color changes to a blue hue of #95C9E8 for demonstration purposes.

The demo page is shown in Chrome 20.0 with a modified screen area of 825 pixels in Figure D below.

Figure D

The same demo page is shown in the iPhone simulation as displayed in Figure E:

Figure E

One more tweak we can make is to extend the real estate of the blog section so that more text and content can be displayed within the screens. Using the calculation again, we can apply a larger percentage for the width, pushing it up to 92.431372549019607843137254901961% from the previous setting of 60.714...%. The media query snippet is displayed below.

@media screen and (max-width:480px) {
    #blog_rwd {
        float: none;
        width: 92.431372549019607843137254901961%;
        background-color:#FFB3B3;
    }
}
We now have an improved RWD as displayed in the iPhone simulation in Figure F:

Figure F

Media query features

The following table highlights the media query features, their associated values, min/max allowed, and a short description. The first five features in the table, which are width, height, device-width, device-height, and orientation, are the most useful and typically the most utilized. You can prefix most features with "min-" and "max-" to indicate minimum and maximum values, such as "min-width" and "max-width". The Min/Max column in the table indicates which features can be modified in this way.

Feature Value Min/Max Description
width Length Yes Width of display area
height Length Yes Height of display area
device-width Length Yes Width of device
device-height Length Yes Height of device
orientation portrait or landscape No Orientation of device
aspect-ratio Ratio (w/h) Yes Ratio of width to height, expressed as two integers separated by a slash (e.g., 16/9)
device-aspect-ratio Ratio (w/h) Yes Ratio of device-width to device-height
color Integer Yes Number of bits per color component (if not color, the value is 0)
color-index Integer Yes Number of entries in the output device's color lookup table
monochrome Integer Yes Number of bits per pixel in the monochrome frame buffer (if not monochrome, the value is 0)
resolution Resolution Yes Density of pixels of output device, express as integer followed by dpi (dots per inch) or dpcm (dots per centimeter)
scan Progressive or interlace No Scanning process used by TV devices
grid 0 or 1 No If set to 1, the device is grid-based, such as a teletype terminal or phone display with only one fixed font (all other devices are 0)

The next post on the topic of RWD will review making your images and other multimedia flexible so they can size to fit any screen in proportion to the resolution and device.

Files used for the demonstration in this part are available for download here.

About

Ryan has performed in a broad range of technology support roles for electric-generation utilities, including nuclear power plants, and for the telecommunications industry. He has worked in web development for the restaurant industry and the Federal g...

4 comments
Shahbaz777
Shahbaz777

i need some help to learn the Media Query only screen / Media Query Screen Min & Max width etc

i shall be very thankful to you if you please help me to get out of this problem to understanding the media query using

Question A
@media screen and (max-width: 320px){
style goes here}

Question B
@media only screen and (max-width: 320px){ style goes here}
is there any difference betweem Question A & B ?
Question C => i saw in sometutorial they using min-width:321 or max-width:419px @media screen and (max-width: 321px){ style goes here}
Can u please explain me, when to use min and when to use maximum. it a request you sir, i want learn responsive please if you help me
thank you so much for your time and help
Looking forward your cooperate

Shahbaz

Williams Brown
Williams Brown

This is a nice post in an interesting line of content.Thanks for sharing this article, great way of bring such topic to discussion.

vtrravikumar
vtrravikumar

Hi Ryan, That was great, elaborate and useful write-up. Thanks for all those details.