CSS media queries are the answer. Back with CSS 2.1 we were introduced to the idea of print style sheets. These are style sheets written just to style how the page should look when it is printed out by using media types. For example:
Media types were a good start, but some devices didn't use them as they were intended, sending information that said they were a desktop browser when they were really a small handheld device. This made it difficult to use them correctly for anything beyond print.
CSS media queries were introduced as part of CSS3 and they improved on the idea of media types by looking at the actual physical specifications being sent from the browser to the computer. A mobile browser could easily pretend to be a desktop browser by simply sending that media type, but it would still have to display the contents in a smaller window.
For example, to send a specific style sheet only to iPhones, you would write:
This tells the browser to use this style sheet if the media is a screen device (rather than print, for example) and has a width of no more than 480 pixels. Note: this will catch any device that has a width less than 480px, even desktop browsers, because it is not a device dependent script. It is just looking at the width and displaying the contents accordingly.
Advantages of CSS Media Queries
You may be thinking that this isn't really that different from using a resolution detection script to pass on the correct style sheet. But there are some definite advantages to using media queries for responsive design:
- CSS media queries go well beyond just testing the resolution. There are, in fact, 13 different features you can evaluate against to get very specific with your designs. Plus media queries let you combine multiple queries to get, for example, only devices that are 600x800px in landscape orientation and not HD.
- You can implement CSS media queries against just one or two rules in an existing style sheet by using the @media rule.
- You can also import media specific style sheets with the @import rule and media queries.