Friday, June 24, 2011

CSS: Style Smartphone using @media query

There are several ways to target handheld devices.  For example, you can use javascript ways by checking the navigator.useAgent like the following

if(navigator.userAgent.match(/Andriod/i)) {
  // add a className to your <body>
}

But among those methods, I found the CSS @media query is my most preferable and generic ways to detect and style the page. However, if you want to target a specific one handheld system, the userAgent way (or the http_user_agent in server side ) will be more useful.

The CSS @media query method will style your page based on your screen size.  And the following is probably what you need most of the time.

/* Smartphones (portrait and landscape) -----------  */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
    /
Styles /
}

/Smartphones (landscape) -----------  */
@media only screen
and (min-width : 321px) {
    /
Styles /
}

/Smartphones (portrait) -----------  */
@media only screen
and (max-width : 320px) {
    /
Styles /
}

/iPads (portrait and landscape) -----------  */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
    /
Styles /
}

/iPads (landscape) -----------  */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
    /
Styles /
}

/iPads (portrait) -----------  */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
    /
Styles /
}

/Desktops and laptops -----------  */
@media only screen
and (min-width : 1224px) {
    /
Styles /
}

/Large screens ----------- */
@media only screen
and (min-width : 1824px) {
    /
Styles /
}

/iPhone 4 -----------  */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
    /
Styles */
}

For more robust and latest media query, please check out the following blog :)
http://www.stuffandnonsense.co.uk/blog/about/hardboiled_css3_media_queries


No comments:

Post a Comment