Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 139 ยท Backgrounds and Effects

Backgrounds

Learn the CSS background properties - color, image, repeat, position, size with cover and contain, attachment - and how to write the background shorthand.

Every box on a page has a background layer that sits behind its content and its border. By default it is transparent, so you see whatever is behind the box. With a few properties you can fill it with a solid color, a photo, a repeating pattern or a gradient, and control exactly how that image is sized and placed.

In this lesson you will learn each background property on its own, then combine them with the background shorthand. The next lessons build on this: Multiple Backgrounds and background-clip stacks several layers, and Gradients turns the background into a canvas for color.

background-color

The simplest background is a single color. It accepts any color value:

CSS
.notice {
  background-color: #fef3c7;
}

The color fills the box's padding area and also runs under the border. You only notice that second part when the border is dashed, dotted or semi-transparent. The margin is never painted; it always stays outside the background.

Even when you use an image, it is a good habit to set a background color too. It shows while the image loads, it shows if the image fails, and it keeps text readable in both cases.

background-image

background-image paints an image behind the content. You point at the file with url():

CSS
.hero {
  background-image: url("/samples/sunset.svg");
}

The image is drawn on top of the background color, so any transparent areas of the image let the color show through. A relative URL inside a stylesheet is resolved against the stylesheet's own address, not the page's, which surprises people when the CSS lives in a different folder.

Background images are decoration. Screen readers ignore them, and there is no way to give them alt text. If an image carries meaning, such as a product photo or a chart, use an <img> element instead (see Images).

background-repeat

When the image is smaller than the box, the browser tiles it in both directions by default. background-repeat controls that:

Value Effect
repeat Tile horizontally and vertically (the default).
repeat-x / repeat-y Tile along one axis only.
no-repeat Paint the image once.
space Tile only whole copies and spread the gaps evenly between them.
round Stretch or squash the tile slightly so a whole number of copies fits.

Small tiles are a lightweight way to make a pattern. Try each value below:

Repeating a tile

Resize the preview, or change the height, and watch space and round adjust: space keeps every tile at its natural size and moves them apart, while round changes the tile size so they always touch.

background-position

background-position says where the image sits inside the box. It takes one or two values: horizontal first, then vertical.

CSS
.badge {
  background-repeat: no-repeat;
  background-position: right top;     /* keywords */
  background-position: 20px 50%;      /* lengths and percentages */
  background-position: right 12px bottom 8px; /* edge offsets */
}
  • Keywords: left, center, right, top, bottom. If you give one keyword, the other axis is center.
  • Lengths move the image's top-left corner that far from the box's top-left corner.
  • Percentages are clever: 25% 75% lines up the point 25% across the image with the point 25% across the box. That is why 50% 50% centers the image perfectly and 100% 100% pins it to the bottom-right corner, whatever its size.
  • Four-value syntax like right 12px bottom 8px measures from any edge you name. It is the cleanest way to say "12px from the right".

There are also background-position-x and background-position-y if you only need to change one axis, for example in a hover state.

background-size

By default an image is drawn at its natural size. background-size changes that, and it is the property you will use most with photos.

  • cover scales the image, keeping its proportions, until it covers the whole box. Some of it may be cropped, but there are never any gaps.
  • contain scales the image until it fits entirely inside the box. Nothing is cropped, but there may be empty bands (which repeat unless you set no-repeat).
  • One length or percentage (200px, 50%) sets the width; the height follows to keep the proportions.
  • Two values (100% 100%) set width and height separately, which stretches the image.

Percentages here are relative to the box (strictly, the background positioning area, which you will meet in the next lesson), not to the image.

cover, contain and stretching

Notice how cover crops the left and right of the landscape image to fill the tall box, while contain leaves gray bands above and below. 100% 100% fills the box but distorts the sun into an oval. For photos, you nearly always want cover together with background-position to choose which part stays visible.

Pair cover with a focal point. If the important part of a photo is near the top, use background-position: center top so cropping removes the bottom instead.

background-attachment

background-attachment decides what the background is fixed to when things scroll:

  • scroll (the default): the background is fixed to the element. When the page scrolls, the element and its background move together. If the element itself has a scrollbar, the background does not scroll with its content.
  • local: the background is attached to the element's content, so it scrolls along inside a scrolling box.
  • fixed: the background is fixed to the viewport. The element acts like a window onto a still image, which creates the classic "parallax" look.
scroll versus local

Use fixed sparingly. Mobile browsers have long treated it inconsistently (iOS Safari ignores it), it can force extra repainting while scrolling, and big motion effects can bother people who are sensitive to motion. Treat it as a nice extra, never as something the design depends on.

The background shorthand

All of these properties can be written in one declaration:

CSS
.hero {
  background: #1e1b4b url("/samples/sunset.svg") center / cover no-repeat;
}

The rules are relaxed. You can list values in almost any order, with two exceptions:

  • background-size must come right after background-position, separated by a slash: center / cover.
  • If you give two "box" keywords (like padding-box content-box), the first is the origin and the second is the clip. You will learn those in the next lesson.

Like every shorthand, background resets every property you leave out to its initial value. That is useful (you get a clean slate) but it also means a later background: red; wipes out an image you set earlier. When you only want to change one part, use the longhand, such as background-color.

Here is a typical hero banner with readable text over a photo:

A hero banner

The dark #312e81 color matters here: if the image never loads, the white text still has enough contrast. Try deleting the url(...) part to check.

Resolution-aware images with image-set()

Phones and many laptops have high-density screens that pack two or three device pixels into every CSS pixel. A 400 ร— 250 photo shown in a 400px box looks soft there, because each image pixel is stretched over several screen pixels. Sending a 1200px photo to everyone fixes that, but wastes data on ordinary screens.

For <img> elements, HTML solves this with srcset (see Responsive Images). For CSS images, the equivalent is image-set(). You list several versions of the image, each with a resolution, and the browser picks the best one for the screen:

CSS
.hero {
  background-image: image-set(
    url("hero-800.jpg") 1x,
    url("hero-1600.jpg") 2x
  );
}

1x means "for screens with one device pixel per CSS pixel", and 2x means two. (x is short for the dppx unit; dpi works too.) The resolution also tells the browser how big the image is in CSS pixels: a 1600px-wide file marked 2x is treated as 800 CSS pixels wide, so background-size: auto shows it at the same size as the 1x file, only sharper.

The browser makes the final choice, and it may weigh more than the screen. On a slow connection or with a data saver turned on, it's allowed to pick the smaller file.

Each sample file below has its file width printed in a colored badge, so you can see which one your screen received:

Picking an image by screen density

On a standard screen you'll see the "400w file" badge; on most phones, "800w" or "1200w". Browser zoom changes the device-pixel ratio too, which is an easy way to test without a second device.

Choosing by file format with type()

Each option can also declare its file type with type(). The browser skips formats it can't decode, so you can offer a modern format with a safe fallback, just like <picture> with <source type>:

CSS
.hero {
  background-image: image-set(
    url("hero.avif") type("image/avif"),
    url("hero.jpg") type("image/jpeg")
  );
}

The first supported option wins, so list the best format first. You can combine both ideas, as in url("hero-2x.avif") 2x type("image/avif").

image-set() works anywhere CSS accepts an image, including mask-image, border-image-source and content. The unprefixed function, with type(), has worked in all major browsers since 2023. Older WebKit-based browsers only understood -webkit-image-set(), which is why you'll still see that prefix in existing stylesheets; writing a plain url() fallback first, as in the demo, covers them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which background-size value fills the whole box without distorting the image, even if some of it is cropped?

    cover scales the image proportionally until no gaps remain, cropping any overflow. contain avoids cropping but can leave gaps, and 100% 100% stretches.
  2. 2. In the shorthand, how do you write a position of center with a size of cover?

    The size always follows the position, separated by a slash.
  3. 3. Why should you set a background-color when using a background photo behind text?

    The color sits under the image and shows whenever the image is missing, so contrast does not depend on the file arriving.
  4. 4. Which value makes a background scroll together with the content of a scrollable box?

    local attaches the background to the element's content. scroll attaches it to the element itself, and fixed to the viewport.
  5. 5. What does background-position: 100% 100% do?

    Percentages match the same point on the image and the box, so 100% 100% lines up both bottom-right corners.

Summary

  • background-color fills the padding area and runs under the border; set one even when you use an image.
  • background-image: url() adds decorative images; meaningful images belong in <img> with alt text.
  • background-repeat tiles by default; no-repeat, space and round change the tiling.
  • background-position uses keywords, lengths, percentages or edge offsets like right 12px bottom 8px.
  • background-size: cover fills without gaps, contain shows the whole image, and two values can stretch it.
  • background-attachment is scroll, local or fixed; use fixed with care.
  • The background shorthand resets everything you leave out; write size after position with a slash.

Next: Multiple Backgrounds and background-clip โ€” stack layers and control where each one is painted.