1. The basic background image
.hero {
background-image: url("photo.jpg");
background-size: cover;
background-position: center;
height: 400px;
}
The element needs a height, because a background does not give it one on its own. cover scales the image to fill the box without distorting it.
2. Stop the image from repeating
By default a background tiles. Turn that off when you use a single photo.
.hero {
background-image: url("photo.jpg");
background-repeat: no-repeat;
background-size: cover;
}
3. Add a dark overlay for readable text
Stack a gradient on top of the image so white text stays legible.
.hero {
background-image:
linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)),
url("photo.jpg");
background-size: cover;
}
The semi-transparent black layer sits above the photo and darkens it evenly.
Common mistakes
- The element has no height. A background image will not show if the box is zero pixels tall.
- A wrong path. The
url()is relative to the CSS file, not the HTML page. - Forgetting
background-size: cover. Without it the image shows at its natural size and may tile.
Frequently asked questions
What is the difference between cover and contain?
cover fills the whole element and may crop the edges; contain fits the entire image inside and may leave empty space around it.
How do I set a background image in HTML directly?
Use a style attribute: <div style="background-image: url(photo.jpg)">. Keeping it in your CSS file is cleaner, though.
Want to understand the layout properties behind this? Work through our free HTML & CSS course.