CSS Background Image

The background-image property places one or more images behind an element's content using the url() function.

Adding a background image

The <background-image> property takes a <url()> pointing to an image file. The image is drawn behind the element's content and, by default, repeats to fill the whole box.

A background image

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url('bg.jpg');
}
</style>
</head>
<body>

<h1>Welcome</h1>
<p>The page background uses an image.</p>

</body>
</html>

Combining with a background color

It is good practice to set a <background-color> alongside the image. If the image fails to load or has transparent areas, the color shows instead, keeping text readable.

Image with a fallback color

<!DOCTYPE html>
<html>
<head>
<style>
.hero {
  background-color: #00643c;
  background-image: url('hero.jpg');
}
</style>
</head>
<body>

<div class="hero">
  <h1>Hero Heading</h1>
</div>

</body>
</html>

Gradients count as images

The property also accepts gradient functions, which the browser treats as generated images. This lets you create smooth color transitions with no image file at all.

A gradient background

<!DOCTYPE html>
<html>
<head>
<style>
.banner {
  background-image: linear-gradient(to right, #00643c, #0a9d63);
}
</style>
</head>
<body>

<div class="banner">
  <p>Banner text</p>
</div>

</body>
</html>
  • Use quotes around the path inside url() for safety
  • Paths are relative to the CSS file, not the HTML page
  • You can layer several images by separating them with commas
Note: By default the image tiles. Control that behavior with background-repeat and lock it in place with background-attachment.