views:

121

answers:

1

I want to change my web page CSS for web browsers running on cell phones, like the iPhone and Android. I've tried something like this in the CSS file:

@media handheld {
  body {
    color: red;
    }
  }

But it doesn't seem to have any effect, at least on the iPhone. How can I write my CSS to work differently on the iPhone etc, ideally without using javascript?

+2  A: 

You can use @media queries:

<link rel="stylesheet" href="path/to/iphone.css" media="only screen and (max-device-width:480px)"/>

This particular version will target the iPhone (and any other device with a screen of max-device-width of 480px.

Apple, for the iPhone, though this is from memory so I can't be entirely sure of its accuracy, chose to disregard the use of handheld or mobile stylesheets, since it, and other iOS devices, were capable of rendering css more or less on a par with desktop browsers, via Safari. For other devices I'm unsure, exactly, how faithful they are, though the A List Apart article (linked-to above) gives a brief run-through of some.


Edited in response to comment, from @Colen:

Hmm, it looks like a lot of new mobile devices have higher resolutions (e.g. droid X is 854x480). Is there any way to detect those? I don't think those are being handled with this query.

I'm unable to say for certain, since I've no access to those devices, however another A List Apart Article: Responsive Web Design notes that:

Thankfully, the W3C created media queries as part of the CSS3 specification, improving upon the promise of media types. A media query allows us to target not only certain device classes, but to actually inspect the physical characteristics of the device rendering our work. For example, following the recent rise of mobile WebKit, media queries became a popular client-side technique for delivering a tailored style sheet to the iPhone, Android phones, and their ilk.

So I presume that they, Android devices, must be target-able by @media-queries, but, as noted, I'm unable to say with any certainty.

To target device-resolution, there is an example of:

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

Further reading: W3 Candidate Recommendation for media queries.

David Thomas
It should be "max-device-width" (you have a space in there), but otherwise this was great. Thanks!
Colen
Thanks @Colen, the typo's now fixed. =)
David Thomas
Hmm, it looks like a lot of new mobile devices have higher resolutions (e.g. droid X is 854x480). Is there any way to detect those? I don't think those are being handled with this query.
Colen