CSS Backgrounds
Background colours, images, repetition, positioning and the handy shorthand that ties them together.
What you will learn
- Add a background image
- Control repeat, position and size
- Use the background shorthand
Background image
Set an image with background-image: url(...). By default it tiles (repeats). Control that with background-repeat, background-position and background-size.
| Property | Common values |
|---|---|
background-repeat | no-repeat, repeat-x, repeat |
background-position | center, top, right bottom |
background-size | cover, contain, 100% 100% |
background-attachment | scroll, fixed (parallax) |
<style>
.hero {
background-image: url('https://picsum.photos/800/300');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
height: 200px; color: white; padding: 20px;
}
</style>
<div class="hero"><h2>Hero Banner</h2><p>cover + center + no-repeat</p></div>This is the recipe behind almost every website banner. Going line by line inside .hero:
background-image: url(...)— loads the photo into the box.background-size: cover— scales the photo so it fills the whole box, cropping any overflow (no blank gaps).background-position: center— keeps the most important part of the image centred when it crops.background-repeat: no-repeat— stops the image tiling; show it once.height,color,padding— give the box a size, white text and inner spacing so the heading sits comfortably on top.
Note: The heading and paragraph sit on top of the image because they are inside the <div>. That is the trademark hero pattern: a big background photo with text laid over it.
The shorthand
Combine everything into one background property to save space.
<style>
.box {
background: #4338ca url('https://picsum.photos/40') no-repeat right center;
color: #fff; padding: 24px; border-radius: 10px;
}
</style>
<div class="box">Shorthand: colour + image + no-repeat + position</div>The single background property packs four things into one line, read left to right: the colour #4338ca, the image url(...), no-repeat so it shows once, and right center as its position. It does exactly what four separate background-* lines would — just shorter. The colour shows wherever the small image does not cover.
Tip: background-size: cover fills the whole area (cropping if needed); contain fits the whole image inside (may leave gaps). cover is the usual choice for banners.
Q. Which value makes a background image fill the whole element, cropping if needed?
✍️ Practice
- Build a hero banner with a background image,
coversize, centred, no-repeat, and a heading on top. - Try
containvscoveron the same image and compare.
🏠 Homework
- Add a hero section with a background image to your landing page project.