CSS - Backgrounds

Overview

Estimated time: 15–20 minutes

Backgrounds add visual richness. Learn to layer images, control positioning, and create complex effects with multiple backgrounds.

Learning Objectives

  • Control background images with size, position, and repeat.
  • Layer multiple backgrounds for rich effects.
  • Use background shorthand effectively.

Details & Examples

Background Properties

  • background-color: solid color fill
  • background-image: url(), gradients, multiple images
  • background-repeat: no-repeat, repeat-x, repeat-y
  • background-size: cover, contain, explicit dimensions
  • background-position: center, top left, percentage values
  • background-attachment: fixed, local, scroll
/* Complex layered background */
.hero {
  background: 
    linear-gradient(rgba(0,0,0,.4), rgba(0,0,0,.6)),
    url(hero.jpg) center/cover no-repeat,
    #1f2937;
}

/* Individual properties */
.pattern {
  background-color: #f8fafc;
  background-image: url(pattern.svg);
  background-size: 40px 40px;
  background-position: center;
  background-repeat: repeat;
}

Try it

Vocabulary

  • Background stack: First declared background appears on top.
  • Fallback color: Always include a background-color as the bottom layer.

Common Pitfalls

  • Forgetting fallback colors when images fail to load.
  • Using background-attachment: fixed can cause performance issues on mobile.

Checks for Understanding

  1. How do you make a background image cover the entire element without distortion?
  2. In multiple backgrounds, which layer appears on top?
Show answers
  1. background-size: cover;
  2. The first one listed appears on top.

Exercises

  1. Create a hero with a gradient overlay over an image using the background shorthand; ensure the gradient layer sits on top.
  2. Build a tiled pattern section with background-size controlling the tile size and a solid fallback color.
Suggested answers
  1. Use: background: linear-gradient(...), url(hero.jpg) center/cover no-repeat, #111827;
  2. Use: background: #f8fafc url(pattern.svg) center/40px 40px repeat;