HTML and CSS Reference
In-Depth Information
After the media type you add conditions with the keyword
and
. Each condition is wrapped in parentheses,
and is based on one of the media features listed in Table
17-1
. You specify the feature's value in the same way
as a CSS property by placing it after a colon. For example, the following media query restricts styles to screens
between
401px
and
600px
wide:
screen and (min-width: 401px) and (max-width: 600px)
All conditions in the query must be true. For example, the preceding query won't work if the display is
700px
wide, even though the minimum width is satisfied.
Some media features don't require a value. To specify a color display, the following is sufficient:
screen and (color)
Similarly,
monochrome
and
grid
can be used without a value. However, each condition involving a media
feature must always be enclosed in parentheses.
Hiding Styles from Browsers that Don't Support Media Queries
Although media queries are new to CSS3, the W3C had the foresight to anticipate them more than a decade
earlier when it drew up the HTML 4.01 specification. Browsers expect media types to be presented as a
comma-separated list. The specification says they should truncate the list immediately before the first
nonalphanumeric character that isn't a hyphen.
So, when an old browser sees one of the media queries in the preceding section, it should simply interpret it
as
screen
. In other words, it should still apply the styles. Unfortunately, IE 8 and earlier won't play ball. If you add
a media query, older versions of Internet Explorer ignore the styles completely.
However, old versions of other, more standards-compliant browsers might follow the rules and apply the
styles, messing up your design. To hide styles from browsers that don't understand media queries, precede the
media type with the keyword
only
like this:
only screen and (min-width: 401px) and (max-width: 600px)
A standards-compliant old browser sees
only
followed by a space, realizes it's not a valid media type, and
ignores the styles. Older versions of Internet Explorer also don't like the look of
only
. Consequently, the styles
are hidden from all browsers that don't understand media queries. Modern browsers recognize
only
as part of a
media query and go on to evaluate the conditions.
■
you can get a lightweight JavaScript polyfill (helper script) that provides basic support for media queries
in iE 6
-
8 from
https://github.com/scottjehl/Respond/
.
it supports only
min-width
and
max-width
, but that's
frequently all you need.
Tip
Specifying Alternative Conditions
There is no
or
keyword to specify alternatives. Instead, you list alternative queries as a comma-separated list.
For example, the following applies styles to visual displays wider than
769px
or printers capable of printing a
minimum of 6 inches wide:
only screen and (min-width: 769px), print and (min-width: 6in)