CodeBlanks Logo Icon CodeBlanks

Background shorthand

CSS course · Beginner · Lesson 41/82

Write all background properties in one line with the background shorthand.

The background shorthand

The background shorthand gathers several background properties on one line. background: #1a1a2e url("/images/hero.jpg") no-repeat center top; sets color, image, repeat and position in a single declaration.

When you use the shorthand, any property you leave out resets to its default. So if you set background-color first and then write background, the color may vanish. Use the shorthand on its own, or last.

background-size

background-size sets the image's size inside the surface. You can give pixels with two values like 200px 100px, or use a keyword.

cover scales the image to fill the box completely, keeping the aspect ratio; any overflow is clipped. contain shows the whole image, leaving some empty space. For a hero section you usually pick cover.

background-attachment

background-attachment controls how the image behaves when the page scrolls. The default is scroll; the image scrolls with the element.

With fixed the image is locked to the viewport; the page scrolls over it, creating a parallax-like effect. In a hero section, fixed makes the image feel still. local scrolls the image with the element's own content.

Exercise Set up the .banner background

Add a .banner class selector. Set its background shorthand to #1a1a2e url("/images/banner.jpg") no-repeat center top, its background-size property to cover, and its background-attachment property to fixed.

Show example solution
/* set up the .banner background */
.banner {
  background: #1a1a2e url("/images/banner.jpg") no-repeat center top;
  background-size: cover;
  background-attachment: fixed;
}

Test yourself

  1. Which is a valid background shorthand?

    • background-image: url("/x.jpg")
    • background-color: #1a1a2e
    • background: #1a1a2e url("/x.jpg") no-repeat center top
    • background-position: center top
    Show answer

    background: #1a1a2e url("/x.jpg") no-repeat center top — Correct. The background shorthand can give color, image, repeat and position in one declaration.

  2. Write the size value so the hero image fills the box

    .hero {
      background: url("/images/hero.jpg") no-repeat center top;
      background-size: ____;
    }
    Show answer
    .hero {
      background: url("/images/hero.jpg") no-repeat center top;
      background-size: cover;
    }
  3. Match each size value to its effect

    cover
    Fills the box, clips overflow
    contain
    Shows whole image, may leave space
    200px 100px
    Two dimensions in pixels
    auto
    Keeps the original size

All lessons in Beginner