CSS - Backgrounds
Overview
Quick links: Exercises • Checks • Print as PDF
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 fillbackground-image
:url()
, gradients, multiple imagesbackground-repeat
: no-repeat, repeat-x, repeat-ybackground-size
: cover, contain, explicit dimensionsbackground-position
: center, top left, percentage valuesbackground-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
- How do you make a background image cover the entire element without distortion?
- In multiple backgrounds, which layer appears on top?
Show answers
background-size: cover;
- The first one listed appears on top.
Exercises
- Create a hero with a gradient overlay over an image using the background shorthand; ensure the gradient layer sits on top.
- Build a tiled pattern section with background-size controlling the tile size and a solid fallback color.
Suggested answers
- Use:
background: linear-gradient(...), url(hero.jpg) center/cover no-repeat, #111827;
- Use:
background: #f8fafc url(pattern.svg) center/40px 40px repeat;