Responsive images with CSS

I wrote last week about using HTML for responsive images. CSS also has the power to support responsive images, with the caveat that as it is applied after the HTML is downloaded, it may be less efficient.

However, it is more flexible and provides greater functionality than HTML alone. So while CSS can be used to detect and respond to viewport width unlike HTML, it can also be used to detect the device resolution.

Here is an example of CSS that can be applied to a specific viewport width. In this case, I'm first setting a default background image, but then using a larger image if the viewport is larger than 40ems.

body {
   background-image: url("cat-small.jpeg");

   @media (min-width: 40em) {
      background-image: url("cat-large.jpeg");
   }
}

 

Note: You should use ems instead of pixels in your CSS media queries.

CSS also allows you to combine conditions. In this case, I'm using a higher quality image if the display is large and high resolution. (192dpi is the resolution of the Mac retina display.)

@media (min-resolution: 192dpi) and (min-width: 40em) {
      background-image: url("cat-large-hq.jpeg");
}

 

You can also combine multiple separate conditions. In this case, I'm apply the high quality image if either of the following is true:

1) The minimum resolution is 192dpi AND the minimum width is 40em.

2) The minimum width is 100em.

@media (min-resolution: 192dpi) and (min-width: 40em),
       (min-width: 100em) {
      background-image: url("cat-large-hq.jpeg");
}

You can add as many conditions as you like separated my commas.