background-image places an image behind an element’s content. You give it a url() that points to the file.
.hero {
background-image: url("images/books.jpg");
}
The examples here use a small built-in image so you can run them without any file. Treat the long url('data:...') as just another image address.
<style>
.box {
background-color: #fff3e0;
background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30"><circle cx="15" cy="15" r="9" fill="orange"/></svg>');
padding: 30px;
}
</style>
<div class="box">The orange dot image is repeated behind this text.</div>
Background image or img tag?
| Use | When |
|---|---|
<img> | The image is content: a product photo, a diagram, a picture in an article. It needs alt text. |
background-image | The image is decoration: a pattern, a texture, a hero banner behind a headline. |
Search engines and screen readers see <img> elements and ignore background images, so meaningful pictures should never be backgrounds.
Always add a fallback color
If the image is slow to load or fails, the browser shows background-color instead. Set one that matches the image and keeps your text readable.
.hero {
background-color: #2c3e50;
background-image: url("images/books.jpg");
color: white;
}
Wrong image path
url() fails quietly. In style.css, paths are relative to the CSS file, not to the HTML page. If style.css lives in a css/ folder, an image in images/ is url("../images/books.jpg").Next you will control how the image repeats, where it sits and how big it is: Background Repeat.