Lesson 52 +10 XP

Background Images

Background Images

You can put a picture behind the whole page, or behind one element, using CSS.

Page background

<body style="background-image: url('bg.jpg');">

Or better, in a style block:

<style>
  body {
    background-image: url("bg.jpg");
  }
</style>

Stop the repeat

By default, a small image repeats over and over to fill the page. Stop that with background-repeat:

body {
  background-image: url("bg.jpg");
  background-repeat: no-repeat;
}

Fill the whole page

Make the image stretch to cover everything:

body {
  background-image: url("bg.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
}
  • background-size: cover: the image fills the whole area.
  • background-position: center: put the image in the middle.

Background on any element

You can add a background image to any box, like a div:

<style>
  .hero {
    background-image: url("sky.jpg");
    background-size: cover;
    padding: 60px;
  }
</style>

<div class="hero">
  <h1>Welcome!</h1>
</div>

Keep it readable!

If text sits on a background image, make sure the text is still easy to read. You can darken the background:

background-color: rgba(0, 0, 0, 0.5);

TL;DR

  • background-image: url('pic.jpg'); adds a background picture.
  • background-repeat: no-repeat stops tiling.
  • background-size: cover fills the area.
  • background-position: center centers it.
  • Works on the page or any element.
  • Keep text readable over images!