Cheat sheet #9

CSS background images

A cheat sheet for web design students. Learn the four key properties that control a background image (background-image, background-repeat, background-position and background-size), and find out how to combine them in a single background shorthand declaration.

The short version

First choose the image, then decide how it repeats, where it’s positioned and how it’s sized. Here’s the most common full-width setup in a single line, starting with a colour as a fallback:

background: #14213d url("../images/hero-mountains.jpg") center / cover no-repeat;
On this cheat sheet

When to use a background image

Backgrounds are for decoration

A CSS background image sits behind an element’s content, and it should only be used for decoration, such as textures, patterns, banner backgrounds, and small icons beside text. An image that carries meaning, such as a product photo, a chart or a team photograph, belongs in the HTML, marked up with <img>.

Use a CSS background for
  • Decorative textures and patterns
  • A banner or hero backdrop behind text
  • Small icons or bullets beside text
Use an HTML img for
  • Photographs and illustrations that are content
  • Anything that needs alt text
  • Images people may want to save or print

Background images have no alt text, so screen readers ignore them. Choose your image formats using cheat sheet 8, and remember that SVG (cheat sheet 7) works well for patterns and icons.

The background-image property

Choose the image

The background-image property takes one or more images. Most commonly, that’s an image file, written with url(). The default value is none.

.hero { background-image: url("../images/hero-mountains.jpg"); } .banner { background-image: linear-gradient(#2a5bd7, #176b3f); } /* gradients are images too */ .card { background-image: url("../images/tile.png"), linear-gradient(#bfd9ff, #2a5bd7); } /* two layers */
url(image)Shown at its natural size, from the top left, and tiled
linear-gradient()A generated image with no file
two layersThe first listed is on top
CSS file is atImage is atWrite
css/main-styles.cssimages/hero-mountains.jpgurl("../images/hero-mountains.jpg")
main-styles.css (top folder)images/hero-mountains.jpgurl("images/hero-mountains.jpg")
Anywhere, on a serverimages/hero-mountains.jpgurl("/images/hero-mountains.jpg") (root-relative)

The background-repeat property

Tile the image, or don’t

If an image is smaller than its box, the browser repeats it to fill the space. The background-repeat property controls this behaviour, and its default value is repeat.

ValueEffect
repeat (default)Tiles in both directions. Tiles at the edges are clipped.
repeat-xTiles horizontally only, in a single row
repeat-yTiles vertically only, in a single column
no-repeatShows the image once
spaceTiles as many whole copies as fit and spreads the gaps evenly. Nothing is clipped.
roundTiles whole copies and stretches or squeezes them slightly so they fit exactly
repeat
repeat-x
repeat-y
no-repeat
space
round
.pattern { background-image: url("../images/dots.png"); background-repeat: repeat; } /* a seamless texture */ .hero { background-image: url("../images/hero-mountains.jpg"); background-repeat: no-repeat; } .divider { background-image: url("../images/wave.svg"); background-repeat: repeat-x; }

Two values set the horizontal and vertical repeat separately, so repeat no-repeat is the same as repeat-x. For photographs and logos, you’ll almost always want no-repeat. Use repeat for small, seamless tiles that join without visible edges.

The background-position property

Place the image in the box

The background-position property sets where the image starts inside its box. Its default value is 0% 0%, the top left corner. Give it two values, horizontal first, then vertical.

Kind of valueExamplesNotes
Keywordsleft, center, right, top, bottomright bottom is the bottom-right corner. Order doesn’t matter for keywords.
Lengths20px 20px, 2rem 0The distance from the top-left corner. A bare 0 needs no unit, but any other number does.
Percentages50% 50%, 100% 0Lines up that point of the image with the same point of the box. 50% 50% centres it. 100% aligns the image’s right edge with the box’s right edge.
Edge offsets (four values)right 10px bottom 10pxAn offset measured from a chosen edge
0 0The default: top left
center
right bottom
50% 100%Centred, at the bottom
20px 20px
right 10px bottom 10px
.hero { background-position: center; } /* centre both ways */ .banner { background-position: center top; } /* keep the top of a tall photo in view */ .note { background-position: left center; padding-left: 2rem; } /* icon beside text */

If you give just one value, it sets the horizontal position, and the vertical position becomes center. Positioning matters most when the image is cropped, as it is with cover (see the next section), because it decides which part of the image stays visible.

The background-size property

Scale the image

The background-size property sets how big the image is drawn. Its default value is auto, which is the image’s natural size. The brown frame on the demo image below makes any cropping easy to see.

ValueEffect
auto (default)The image’s natural size
coverScales the image, keeping its proportions, until it covers the whole box. Any excess is cropped. The usual choice for hero backgrounds.
containScales the image, keeping its proportions, until it fits entirely inside the box. Empty space may be left, and it is filled by tiling unless you use no-repeat.
One length or %: 100px, 50%Sets the width. The height follows automatically, so the proportions are kept. A percentage is of the box, not of the image.
Two values: 100px 40px, 100% 100%Sets width and height. The image is stretched if the proportions differ.
autoNatural size, so it is cropped
coverFills the box, crops the rest
containShows it all, leaving gaps
100pxWidth set, height follows
50%Half the box’s width
100% 100%Stretched out of shape*
Dobackground-size: cover; background-size: contain; background-size: 1.5rem;
Watch outbackground-size: 100% 100%; /* distorts */ background-size: 500px; /* a small raster image goes blurry */

A box needs a size for cover to work. An empty div has no height, so its background will be invisible. Give it a min-height, or put some real content inside it. Note too that scaling a raster image up makes it blurry, so start with an image that’s at least as large as its display size.

*SVG background images may not stretch. For more information, see Scaling SVG backgrounds at MDN Web Docs.

The background shorthand

Combine the properties in one declaration

The background shorthand sets all these properties in a single declaration. The values go in the order shown below, and every part is optional.

background: color image position / size repeat; background: #14213d url("../images/hero-mountains.jpg") center / cover no-repeat;
PartSetsExample
colourbackground-color#14213d
imagebackground-imageurl("../images/hero-mountains.jpg")
positionbackground-positioncenter
/ sizebackground-size/ cover
repeatbackground-repeatno-repeat
optional extrasbackground-attachment, background-origin, background-clipfixed
/* The banner above */ .hero { background: linear-gradient(rgb(20 33 61 / 45%), rgb(20 33 61 / 45%)), /* top layer: a dark overlay */ #14213d url("../images/hero-mountains.jpg") center / cover no-repeat; /* bottom layer, with the colour */ }

Rules of the shorthand:

The big gotcha: shorthand resets everything

Any part that you leave out is reset to its default value, which wipes out anything you set earlier. This catches out a lot of students.

Do: set everything you need.hero { background: #14213d url("hero.jpg") center / cover no-repeat; } /* or tweak one property afterwards */ .hero:hover { background-size: 110%; }
Don’t: the second rule undoes the first.hero { background-color: #14213d; background-size: cover; background-repeat: no-repeat; } .hero { background: url("hero.jpg"); } /* colour, size and repeat are all reset to their defaults */
PropertyDefault (what the shorthand resets to)
background-colortransparent
background-imagenone
background-position0% 0% (top left)
background-sizeauto
background-repeatrepeat
background-attachmentscroll
Use the shorthand when
  • You’re setting up a background from scratch.
  • You want compact, readable CSS.
  • You’re defining several layers together.
Use the longhand when
  • You’re changing one property, such as in a hover state or media query.
  • You don’t want to reset the others.
  • You want to be as explicit as possible while learning.

Related properties

PropertyWhat it doesValues
background-colorThe colour behind (and visible through) the image. Always provide one as a fallback, and for contrast.Any colour (see cheat sheet 5)
background-attachmentWhether the image scrolls with the pagescroll (default), fixed (stays still: often janky on mobile), local
background-originThe area that position and size are measured frompadding-box (default), border-box, content-box
background-clipHow far the background extendsborder-box (default), padding-box, content-box

Common patterns

GoalCSS
Full-width hero photobackground: #14213d url("../images/hero.jpg") center / cover no-repeat; with a min-height
Photo with readable text on topA semi-transparent gradient layer above the image, as in the banner above
Seamless texturebackground: #eef2f7 url("../images/paper.png"); (the default repeat)
Icon beside textbackground: url("../images/info.svg") left center / 1.25rem no-repeat; plus padding-left: 2rem;
Whole image visible in a fixed areabackground: url("../images/logo.svg") center / contain no-repeat;
Decoration in a cornerbackground: url("../images/leaf.svg") right bottom / 6rem no-repeat;

Text, contrast and accessibility

Common mistakes

MistakeFix
The image doesn’t appear because the path is relative to the HTML pageWrite the path relative to the CSS file, such as ../images/hero.jpg
A photo repeats like wallpaperAdd no-repeat
cover on an empty element shows nothingGive the element a min-height or content
A later background shorthand wipes out earlier longhandsSet every part you need, or use longhands to adjust
background: url(a.jpg) cover;Size needs a position and slash: center / cover
A position of 20 20 with no unitsWrite 20px 20px (only 0 needs no unit)
Stretching with 100% 100%Use cover or contain to keep proportions
White text on a light photoAdd an overlay layer or a solid fallback panel
A content photo set as a backgroundUse an <img> with alt text
background-attachment: fixed on mobileAvoid it. It is unreliable on phones and tablets.

Check before you upload

Learn more

Tip: in your browser’s dev tools, edit the background-position and background-size values live in the Styles panel to see exactly how each one moves and scales the image.