2010-10-21

How to specify different CSS rules based on device screen size (i.e. for the iPad)

I was working on a web app where I wanted the appearance to be very different on my iPad than it was on my laptop. After some research I found this article:

Detecting device size & orientation in CSS

That describes how you can include code in a CSS stylesheet that will apply designated rules only if the device screen (or browser viewing area) meets certain criteria. For example (from the article):

@media only screen and (max-width: 999px) { /* rules that only apply for canvases narrower than 1000px */}

@media only screen and (device-width: 768px) and (orientation: landscape) { /* rules for iPad in landscape orientation */}

@media only screen and (min-device-width: 320px) and (max-device-width: 480px) { /* iPhone, Android rules here */}


CSS put inside the brackets in these examples would only apply if the specified criteria are met. Also, the CSS rules apparently work on the fly, so if the user resizes their browser screen the appropriate rules will be applied without refreshing.

I also found a reference article on these "media queries" for Firefox. Much of what is in this article applies to other browsers since I believe it is derived from the CSS 3 specification.

Media Queries

Note that this article only uses these media queries to select an alternate style sheet but as far as I can tell you can also use them to apply a block of rules enclosed in curly brackets after the query as shown in the example above and the first article.

There is also an Apple article that includes a section on conditional CSS:

Optimizing Web Content

After doing some experimenting, it appears that once a CSS property is specified the only way to remove it using a media query is to specifically specify a new value for the property. In other words, if you specify a bunch of properties for the ".main" class in your style sheet, and then in your media query block just specify:

@media only screen and (max-width: 999px) { .main {;}}

Then all the rules you specified for .main are still going to apply even when the media criteria is met because they were not individually countermanded.

I experimented around with different media queries to distinguish between my iPad and my laptop and in the end this seemed to work so that the rules were only applied on my iPad, and the rules were applied regardless of my iPads orientation:

@media only screen and (max-device-width: 1024px)
{/*max-device-width: 1024px seems to only select the iPad*/}