Codectionary / Developer documentation / CSS

Background Properties

Background properties control an element's background color and image. background-image sets one or more images, background-size controls their scaling, background-position controls placement, and background-repeat controls tiling. Multiple backgrounds can be layered by comma-separating values.

Syntax

background-image: url();
background-size: cover | contain | length;
background-position: value;

Examples

A Full-Bleed Cover Image

The classic hero-image pattern.

.hero {
  background-image: url("banner.jpg");
  background-size: cover;       /* fills the box, cropping as needed */
  background-position: center;   /* keeps the image centered while cropping */
  background-repeat: no-repeat;
}

Layering Multiple Backgrounds

Combining a gradient overlay with an image, comma-separated from front to back.

.overlay-hero {
  background-image:
    linear-gradient(rgba(0,0,0,0.4), rgba(0,0,0,0.4)),
    url("banner.jpg");
  background-size: cover;
}

Parameters and values

  • background-color (color): Solid background fill, shows if the image fails to load
  • background-image (url() | gradient): One or more layered background images
  • background-size (cover | contain | length): How the image is scaled within the element
  • background-position (keyword | length): Where the image is placed within the element
  • background-repeat (repeat | no-repeat | repeat-x | repeat-y): Whether/how the image tiles

Best practices

  • Always set a background-color as a fallback alongside background-image, in case the image fails to load or is still loading
  • Use background-size: cover for full-bleed hero images, and contain when the entire image must always be visible without cropping
  • Layer a semi-transparent gradient over a background image to ensure text placed on top remains readable
  • Prefer an actual <img> element with alt text over a CSS background-image when the image is meaningful content, not decoration

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation