HTML and CSS Reference
In-Depth Information
Using Media Queries to Target Different Devices
As the use of mobile devices such as smart phones and tablets increases, more people are accessing web
sites over mobile devices. A problem in such cases is that a web page designed for a desktop browser
doesn't look as expected when viewed on a mobile browser. For example, a hover menu with a sleek
animation effect that looks stunning in a desktop browser may not display correctly in a mobile browser
and may appear overlapped and disproportionate. A traditional approach to deal with users accessing a
web application via both desktop computers and mobile devices is to develop two versions of the web
application—a normal version and a mobile version. Although this approach works, the downside is that
you need to maintain two different versions of the web application.
CSS3 offers some help when you're targeting your web application to mobile devices. Support for
media queries allows you to detect certain features of the requesting device and apply a styling rule
accordingly. This way, you don't need to create different versions of the web site targeting different devices.
You can dynamically change the styles being applied to page elements in two ways:
• You can attach a different style sheet ( .css ) to a page if the requesting device meets
certain criteria.
• You can change the CSS rules, depending on the requesting device.
n Note This topic isn't about developing web sites for mobile devices and hence discusses media queries only to
make you familiar with this new CSS3 feature. See for more details.
Typically, media queries use the following parameters to change the style rules being applied to a page
or element:
• Minimum and maximum width of the browser window ( min-width and max-width )
• Width of the device screen ( max-device-width )
• Orientation of the device screen (horizontal or vertical: orientation )
• Height of the device screen ( device-height )
Changing a Style Sheet Using Media Queries
Using media queries and device properties as discussed in the preceding section, you can attach a
different style sheet to a web page at runtime. Suppose you have two style sheets Desktop.css and Mobile.
css that contain CSS style rules to be used when the target is a desktop or a mobile device, respectively. You
want to attach Desktop.css to a web page if it's being viewed by a device with a minimum width of 800
pixels (if a device's screen is at least this wide, chances are it's a desktop computer). Along the same lines, if
the screen width is a maximum of 480 pixels (a typical value for mobile phones), then you wish to attach
Mobile.css . You can accomplish this task by referring to the style sheets as follows:
<link rel="stylesheet" type="text/css"
media="(min-device-width:800px)" href="Desktop.css" />
<link rel="stylesheet" type="text/css"
media="(max-width:480px) and (orientation:portrait)" href="Mobile.css" />
Search WWH ::

Custom Search