HTML and CSS Reference
In-Depth Information
phones, the width and height can swap dimensions just by changing the orientation of the screen.
What's a poor web designer to do?
A new CSS property known broadly as
media queries
is here to help. A media query is a way to
modify the CSS applied according to specified properties of the viewing device. In other words, a
media query may ask, “How big is your screen?” and then use an appropriate CSS style sheet that
depends on the answer.
Just as you have more than one way to include a style sheet, you have more than one way to use
media queries.
If you're looking to switch entire style sheets — which is an approach most web designers take —
your two options are the
@import
declaration and the
<link>
tag. Take a look at the
@import
tech-
nique first with some sample code:
@import url(styles/phone.css) screen and (max-width:320px);
Translated into English, this CSS declaration says, “Import the phone.
css style sheet from the styles folder if the site visitor is using a screen
with a maximum width of 320 pixels.” The
max-width
property sets
the conditional maximum value for the width. To make the most of the
phone screen design, the navigation as well as the entire page might be
redesigned, as shown in Figure 28-2.
Along with
max-width
, there is a corresponding
min-width
property
as well, which might come into play if you wanted to use a specific style
sheet when the site is viewed through a desktop system:
@import url(styles/desktop.css) screen and (min-width:769px);
But what about tablets, which are bigger than a phone and smaller than
a desktop? To load a tablet-specific style sheet, you can use both the
min-
width
and
max-width
properties, like this:
@import url(styles/tablet.css) screen and (min-width:321px) and
(max-width:768px);
FiGure 28-2
The
and
keyword allows you to combine different query parameters.
If you'd prefer to use the
<link>
tag (as I do), equivalent techniques exist
for loading different external style sheets for devices with different screen dimensions. For a phone
with a maximum width of 320 pixels, your code would look like this:
<link href=”styles/phone.css” rel=”style sheet” type=”text/css” media=”only
screen and (max-width: 320px)” />
As you can see, a
media
attribute is used to contain the query. Note that the keyword
only
is incor-
porated here. For desktop systems, you could use this code:
<link href=”styles/desktop.css” rel=”style sheet” type=”text/css” media=”only
screen and (min-width: 769px)” />