DevAcademy
LearnCSSCSS Backgrounds
BeginnerCSS

CSS Backgrounds

Learn how to set background colors and images, and control their size, position, and repetition.

Reading Time

14 min

Lesson

Lesson 9 of 30

Background Color

The background-color property sets a solid color behind an element’s content and padding.

Background Color Example

<style>
  .box {
    background-color: #ffeaa7;
    padding: 20px;
  }
</style>

<div class="box">A box with a background color</div>
Output

Background Properties

PropertyPurpose
background-colorA solid background color
background-imageAn image, gradient, or pattern
background-sizeHow the image is scaled (cover, contain, or a size)
background-positionWhere the image is placed within the box
background-repeatWhether the image tiles (repeat, no-repeat)

Background Image

<style>
  .banner {
    height: 150px;
    background-image: linear-gradient(45deg, #667eea, #764ba2);
    background-size: cover;
    background-position: center;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
  }
</style>

<div class="banner">Banner with a gradient background</div>
Output

The background Shorthand

Instead of writing each background property separately, the background shorthand combines several of them into a single declaration.

background Shorthand

.hero {
  background: url("hero.jpg") center / cover no-repeat, #333;
}
/* image, position, size, repeat, then a fallback color */

background-size: cover vs contain

cover scales the image to fully cover the box, cropping if needed. contain scales it to fit entirely within the box, potentially leaving empty space.

Best Practice

Always set a fallback background-color close to your image’s dominant color, so the layout looks acceptable while the image loads or if it fails to load.

Interview Questions

Quick Quiz

1. Which value makes a background image fully cover its box, cropping if necessary?

2. Which property prevents a background image from tiling?

3. What is the benefit of setting a fallback background-color with an image?