Background & retina images

A quick overview of using CSS background images on a site and when they should be used.

Go fullscreen: ⌃⌥F

Background & retina images

Background vs. foreground

  • <img> is for content
    The user would have difficulty understanding the page without this image

  • background-image is for decoration
    The user wouldn’t miss the image if it didn’t load

No alternatives

Background images don’t have alt="" tags, because they aren’t important to the content

HTML
<div class="bg">
  <h1>Background images!</h1>
</div>
CSS
.bg {
  background-image: url("../images/pattern.svg");
  border: 4px solid steelblue;
}
HTML
<!--
  If the element doesn’t take up space,
  the image isn’t visible
-->
<div class="bg"></div>
CSS
.bg {
  background-image: url("../images/pattern.svg");
  border: 4px solid steelblue;
}
CSS
.thingy {
  /* Link to an image in another folder */
  background-image: url("../images/pattern.svg");

  /* Control how the image repeats: `repeat`, `no-repeat` `repeat-x` `repeat-y` */
  background-repeat: no-repeat;

  /* Change the size of the image: `width height` */
  background-size: 64px auto;

  /* Change the location of the image: `horizontal vertical` */
  background-position: left center;
}
HTML
<div class="bg">
  <h1>Gradients!</h1>
</div>
CSS
.bg {
  background-image: linear-gradient(to bottom, red, darkred);
  color: #fff;
}

Retina images

  • With so many screens being Hi-DPI it’s a good idea to optimize images
  • We need to do it in a way that doesn’t make our website slower

Retina image solutions

  • <img srcset="…" alt="…">
  • <picture>
  • “Compressive JPGs”

Compressive JPGs

  • Recognizes that the images are scaled down
  • The quality can be much lower to save download time—yet still look good

Compressive calculations

(maximum width in browser)
× 2
===============================
(image dimensions in Photoshop)

Photoshop Save for Web JPG quality: 20%–30%

Start

Background & retina images

A quick overview of using CSS background images on a site and when they should be used.