The Book of CSS3 - A Developer\'s Guide to the Future of Web Design (2nd edition)

(C. Jardin) #1
Media Queries 15

This flexibility makes serving higher-resolution background images to
browsers with higher pixel density easier, as you can see in this code:

 E { background-image: url('image-lores.png'); }
 @media (min-resolution: 1.5dppx) {
background-image: url('image-hires.png');
 background-size: 100% 100%;
}

The first rule () means browsers on devices with a “standard” (or
low-resolution) pixel ratio will use the standard image (image-lores.png),
whereas devices with a DPR of at least 1.5 will use the high-resolution image
(image-hires.png) instead (). Note the use of the unfamiliar background-size
property here (); this property should be used with high-resolution images
to ensure they aren’t displayed larger than the element they are applied to
(I introduce background-size fully in Chapter 8).
Chrome, Firefox, and Internet Explorer 10+ all support the resolution
media feature, although IE unfortunately hasn’t implemented the DPPX
value; to accommodate IE, you should use DPI, multiplying the required
DPR by 96 (the DPI value of a standard screen). Here’s an example:

@media (resolution: 1.5dppx), (resolution: 144dpi) { rules }

Safari doesn’t support resolution, instead using a proprietary media
feature called -webkit-device-pixel-ratio (along with max- and min- variants),
which takes as a value a single, unitless number that is the targeted DPR. So
to accommodate all modern browsers, use this rule:

@media (resolution: 1.5dppx), (resolution: 144dpi), (-webkit-device-pixel-ratio: 2) { rules }


The resolution rule was implemented in the WebKit engine at the end
of 2012, so I’m disappointed to not see it released in Safari at the time of
writing, almost two years later. Hopefully this oversight will be rectified in
the near future.

Device Width and Height


The width and height media features are related to the dimensions of the
browser viewport, but that viewport isn’t always as big as the screen it’s
displayed on. If you need to target the physical screen size rather than the
viewport size, you can use the device-width and device-height properties and
their related min- and max- variants. You won’t use these too often, but to
explain why, I need to digress.
In the previous section, I explained the difference between CSS pixels
and physical pixels. The width media feature is measured in CSS pixels,
Free download pdf