CSS Backgrounds

Background colours, images, cover/contain, positioning and layers.

Lesson 7 of 49Beginner30 min read

A website feels more complete when its sections have clear colours, attractive images, and readable text. CSS backgrounds help create these visual areas without adding extra decorative elements to the HTML. You can give an entire page a soft colour, place a photograph behind a heading, or add a gentle gradient to a button or card. The background stays behind the element's content, so the text, icons, and other elements remain in front.

The CSS background property is a shorthand for several settings that work together. Some control what appears behind the content, while others decide how a background image fits, where it sits, and whether it repeats. Learning these settings separately makes the shorthand much easier to understand later. You do not have to memorize every property at once. Start with a background colour or image, then adjust its size and position until it looks right.

A common use is a hero background image, which creates a large visual banner near the top of a page. Product cards, headers, sidebars, and landing-page sections also use backgrounds to separate information and guide attention. In this lesson, you'll learn how to add background colours and images in CSS, choose between cover and contain, control repeating and scrolling, combine multiple layers, and avoid mistakes that make images disappear or text difficult to read.

Background image or HTML image? Use CSS backgrounds primarily for decoration. A meaningful photograph, product picture, chart, or diagram normally belongs in an HTML <img> element with suitable alternative text. CSS background images are not announced as images by screen readers. Choosing the right approach makes your page easier to understand for everyone, not just people who can see the design.

Understanding the CSS background properties

CSS provides several background properties because a single image or colour can behave in different ways. For example, a photograph may need to fill a wide banner, while a small pattern should repeat across a page. Instead of making every decision in one complicated declaration, you can set the individual properties and see what each one changes.

PropertyWhat it controlsCommon values
background-colorThe colour behind an elementlightblue, #1f2937, rgb(30 41 59)
background-imageThe image or gradient usedurl("photo.jpg"), linear-gradient(...)
background-sizeThe size of the background imagecover, contain, 200px auto
background-positionWhere the image is placedcenter, top right, 50% 20%
background-repeatWhether and how the image tilesrepeat, no-repeat, repeat-x
background-attachmentWhether an image scrolls with contentscroll, fixed, local
background-originThe box from which an image is positionedpadding-box, border-box, content-box
background-clipHow far the background is paintedborder-box, padding-box, content-box

These properties work on a wide range of HTML elements, including body, div, section, and header. A background does not create extra space or give an empty element a height. The element must already have content, padding, a height, or another reason to occupy space before its background becomes visible.

You will also notice that some backgrounds use images and others use gradients. Both can be assigned with background-image, and they can be stacked as layers. This is useful when you want to darken a photograph without editing the image file itself. Most CSS background settings are not inherited automatically by children, which means a parent section's background does not become each child's separate background.

CSS background-color: Adding a background colour

The easiest way to style an element is with background-color in CSS. It fills the element's background painting area with a single colour. You can write a named colour such as lightblue, a hexadecimal value such as #e0f2fe, or a modern RGB value such as rgb(224 242 254). Each format describes a colour; the best choice depends on how your project organizes its design system.

Background colours are useful for navigation bars, cards, form sections, warning messages, and the page itself. For a beginner, a solid colour is often a better starting point than an image because it makes spacing and text contrast easier to judge. It also loads without an additional image request. You can use a pale background behind dark text or a dark background behind light text to separate important parts of a layout.

By default, the background colour can extend underneath an element's border, depending on the border and clipping settings. It also fills the padding area. The margin sits outside the element and is not coloured by its background. This distinction is important when you notice a gap between neighbouring cards: the margin creates separation, while padding creates space inside the coloured area.

A background colour also acts as a useful fallback behind a CSS background image. If the image fails to load or takes time to appear, the colour remains visible. Choose the fallback with the text colour in mind so that visitors can still read the section. A decorative photograph should never be the only thing making the content understandable.

CSS background-image: Adding images and gradients

The background-image property places one or more images behind an element's content. For a file, you use the url() function, such as background-image: url("images/forest.jpg");. The browser loads the image and draws it within the element's background area. This is different from inserting an HTML image: the background does not change the document's content or provide meaningful alternative text.

An image path can be relative or absolute. With an external stylesheet, a relative path is normally resolved from the CSS file's location, not from the HTML page. This is a common reason a background image does not show up even though the file exists. Check the folder structure, spelling, capitalization, and browser developer tools if an image is missing. An external image URL may also fail because of network restrictions or server problems.

Without other instructions, the image is drawn at its natural size and repeats if necessary. A small texture may therefore appear many times across a large section. A large photograph may extend beyond the area and look cropped. You control these behaviours with background-size, background-position, and background-repeat, which are explained separately below.

CSS gradients are another type of background image. A linear-gradient() can move smoothly from one colour to another, while a radial-gradient() spreads colours outward from a centre or other position. Gradients are generated by the browser, so they do not require a photograph. They are useful for subtle depth, attractive banners, or transparent overlays placed above a photo. Remember that background-color accepts a single colour; a gradient belongs in background-image or the background shorthand.

CSS background-repeat: Controlling image tiling

When you use a background image in CSS, the default background-repeat value is repeat. If an image is smaller than its background area, the browser draws additional copies side by side and above or below one another. This is called tiling. Repetition can be a good thing for tiny textures, dots, grids, or patterned paper effects. It is usually not what you want for a large photo.

Set background-repeat: no-repeat when you want a single copy of the image. The repeat-x value repeats the image horizontally, while repeat-y repeats vertically. These options suit decorative stripes, borders, and repeating accents. CSS also supports space and round, which distribute or resize repeated tiles in different ways. Beginners usually need repeat and no-repeat first.

Turning off repetition does not automatically make the image fill the element. A small image can remain small and leave uncovered areas, where the background colour appears. If your goal is a full-width banner, combine no-repeat with a suitable background-size, usually cover. If you want an icon-like illustration that stays fully visible, contain may fit better.

As you work, think about the purpose of the image. A repeating pattern should connect smoothly between its edges. A landscape photograph generally should appear once. These choices influence how polished and calm a design feels, especially on mobile screens where repetition can become more obvious.

CSS background-size: cover vs contain

The background-size property decides how a background image is scaled inside an element. Its two most useful values are cover and contain. They can look similar when an image and an element have the same proportions, but they behave differently when the proportions change. Understanding that difference is essential for responsive backgrounds.

background-size: cover makes the image large enough to fill the entire background positioning area while keeping its proportions. No empty background area is left because of the image's size, but parts of the image may fall outside the box and become cropped. This makes cover a popular choice for hero sections, card headers, and large banners. A wide image inside a tall mobile banner may lose a substantial amount of its left and right edges.

background-size: contain scales the image until the complete image fits inside the area without changing its proportions. Nothing is cut off because of sizing, but the box may have unused space above and below or on the sides. If repetition is enabled, the contained image can appear more than once, so pair it with background-repeat: no-repeat when you want a single complete image. Contain is often better for decorative illustrations and logos that should not be cropped.

You can also set a specific size, such as 200px auto, or percentages. auto helps preserve the image's natural aspect ratio when one dimension is specified. Avoid forcing unrelated width and height values unless stretching is intentional, because that can distort a photograph. There is no universal best background size: choose based on whether filling the available space or preserving the whole image matters more.

CSS background-position: Choosing what stays visible

After setting an image's size, use background-position to decide where the image sits within the element. Common values include center, left top, right bottom, and center top. You can also use percentages, pixel lengths, or combinations of keywords and offsets when a design needs more control.

This setting is especially helpful with background-size: cover, because some cropping is often unavoidable. Imagine a photo of a person standing near the right edge. A centred background may crop out the person on a narrow screen. Moving the background toward the right can help keep the subject in view. A landscape photo with important details at the top might work better with center top rather than the default position.

With no-repeat and contain, positioning also determines where visible unused space appears. You might centre a logo in a card or align a small pattern to the lower-right corner. The property does not move the element or its text; it only changes the placement of the background image inside that element.

It is useful to remember that 50% 50% means centred, not that the image starts halfway across the box. Percentage positioning aligns corresponding points in the image and the positioning area. Beginners do not need the calculation to use it, but this explains why percentages often behave more naturally than fixed pixel offsets when the layout changes.

CSS background-attachment: Scroll, fixed and local

The background-attachment property controls how a background moves when content scrolls. The normal value is scroll, where the background is attached to the element and moves with that element in the page. For most page sections and cards, this default is exactly what you need.

Using background-attachment: fixed attaches the image to the viewport rather than letting it travel normally with the element. On a long page, this can create a stationary-image effect while surrounding content moves. Designers sometimes call this a parallax-like background, although it is not the same as a full parallax animation. Support and rendering behaviour can vary on mobile browsers, so test the result rather than assuming it will look identical everywhere.

The local value is different: it makes the background scroll with an element's own scrollable content. This can be relevant for a panel with an internal scrollbar. It is not usually necessary for a basic hero section. Keeping the default is generally the simplest choice unless the design has a clear reason to change the scrolling behaviour.

Avoid using fixed backgrounds only because they seem impressive. Large images, unusual cropping, and scrolling effects can reduce readability or create performance issues on some devices. First build a clear and responsive layout; add scrolling treatments only after confirming they improve the experience.

CSS background-origin and background-clip

Two less familiar properties control where backgrounds start and how far they extend: background-origin and background-clip. Their names sound similar, but they answer different questions. background-origin chooses the reference box used for positioning and sizing a background image. background-clip limits the region where the background is painted.

CSS elements have a content box, a padding area, and a border area. With background-origin: padding-box, an image is positioned relative to the padding box, which is the default. The border-box value includes the border area in the positioning box, while content-box uses the content area. These differences are easier to notice on elements with thick padding or borders. They are useful when a pattern must line up precisely with part of a card.

background-clip determines the painting boundary. Its normal value is border-box, allowing the background to extend behind the border. padding-box stops the background at the outside edge of the padding area, and content-box limits it to the content box. This is particularly helpful for creating borders that appear separate from the element's coloured interior.

Do not confuse the two: changing the origin does not necessarily prevent a background from being painted behind a border. Also, background-origin has no effect on background images using background-attachment: fixed. You can leave both properties at their defaults for ordinary page sections and introduce them when you need detailed control over the box model.

CSS background shorthand: Writing properties together

The CSS background shorthand lets you combine several settings in one declaration. Instead of writing a separate line for the colour, image, position, size, and repetition, you can write a compact background value. This is convenient for small stylesheets and reusable design components, but it is easier to get right after learning the individual properties.

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

Here the dark colour is a fallback, the url() selects an image, center places it, cover scales it, and no-repeat prevents tiling. The slash matters: when you include a background size in the shorthand, it follows the position and is separated by /. Without this structure, the declaration may be invalid or behave differently than expected.

One important detail is that the shorthand resets background settings you leave out. Suppose you set background-size: cover, then later write background: url("photo.jpg"). The second declaration resets the size to its default. A safer approach is to keep all related shorthand settings together or use the longhand properties when you plan to change only one part.

Shorthand is not automatically better for beginners. A few extra clear lines often make debugging easier. Use it when the complete background configuration is short and understandable, and switch to individual properties if you need to explain or adjust each setting separately.

Multiple CSS background images and gradient layers

CSS supports multiple background images on one element. You list layers separated by commas, and the first layer appears on top of the later layers. This makes it possible to place a transparent gradient over a photograph, combine a decorative texture with a colour, or position several small graphics in different corners without adding extra HTML elements.

A very common design uses a gradient layer to darken an image behind a heading. The top gradient needs some transparency so the photo remains visible underneath. If the top layer is fully opaque, it hides the lower image. A solid background-color appears underneath all image layers and can only be specified as part of the final layer in the shorthand.

Different layers can have different sizes, positions, and repeat settings. For example, a small icon may sit at right top while a photo covers the section behind it. Each layer's settings correspond to its position in the comma-separated lists. If this becomes difficult to read, use separate longhand declarations or keep the design simple.

Gradients are useful because they adapt to different screen widths without an additional image file. They can improve text readability, but they do not replace checking contrast on real devices. Multiple backgrounds are most effective when each layer has a clear purpose rather than being added solely for visual complexity.

Responsive CSS background images and readable text

A responsive background image should look intentional on both wide monitors and narrow phones. The element's shape changes with the screen, and this affects the visible part of an image using cover. A picture that looks perfect on desktop may crop out its main subject on mobile. Test several widths, then adjust background-position, the section's height, or even the image choice if needed.

For hero banners, give the section enough height or padding for the text to breathe, but do not force such a tall fixed height that content overflows on smaller devices. Use flexible spacing where possible. Backgrounds are painted behind the content, so an element's content and layout still determine whether the banner is comfortable to read.

Text placed over a photograph is an accessibility concern. Even if white text is readable over one dark area, another crop may place the words over a bright sky. Add a dark or light overlay, use a solid text panel, or change the photo. Check the contrast of headings, buttons, and body text rather than relying on text shadows alone. Keep any vital information in HTML text, not only inside the image.

Large image files can also slow a page. Compress decorative photos, choose suitable dimensions, and avoid loading a huge image for a small card. CSS controls the display size, not the amount of image data downloaded. A simple background colour or gradient may be a better choice when a photograph adds little value.

Common CSS background mistakes and how to avoid them

Most CSS background image problems come from a few predictable causes. The first is a missing or incorrect file path. An image URL inside an external stylesheet is typically relative to that stylesheet, so moving CSS into another folder can break a previously working link. Check network requests and computed styles in browser developer tools if you see only the fallback colour.

Another common mistake is forgetting url(). An ordinary quoted filename is not valid as a background image value. The browser may ignore the declaration rather than displaying the expected photo. Also remember that a background does not give an empty div any size. If the element has no content and no specified dimensions, there may be nothing visible to paint.

Unexpected tiling happens because background-repeat defaults to repeat. Unexpected cropping often comes from cover, which fills the box by trimming edges when necessary. If an important subject is missing, try adjusting background-position before changing the whole layout. If every part of an illustration must be visible, consider contain or a meaningful HTML image instead.

Finally, watch the order of declarations. A later background shorthand can override earlier longhand values. Use clear, consistent CSS, test with the actual images and screen sizes your site will use, and keep a readable background colour underneath images as a fallback.

CSS Backgrounds Syntax

Background properties


.hero {

  background-color: #222;

  background-image: url("beach.jpg");

  background-size: cover;

  background-position: center;

  background-repeat: no-repeat;

}

CSS Backgrounds Summary

  • CSS backgrounds can be solid colours, images, gradients, or multiple stacked layers.
  • background-color sets a colour; background-image loads a decorative image or gradient.
  • background-size: cover fills an area and can crop; contain fits the whole image and may leave space.
  • background-position controls image placement, while background-repeat controls tiling.
  • background-attachment changes scrolling; background-origin and background-clip control box positioning and painting.
  • The background shorthand resets omitted values, so declaration order matters.
  • Use HTML images for meaningful content; keep decorative CSS backgrounds responsive and readable.

CSS Backgrounds Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

A hero banner


.hero {

  min-height: 220px;

  padding: 30px;

  color: white;

  font-family: sans-serif;

  background-color: #1f2937;

  background-image: url("https://picsum.photos/id/1036/900/500");

  background-size: cover;

  background-position: center;

}

.hero h1 {

  margin: 0 0 6px;

  text-shadow: 0 2px 8px rgb(0 0 0 / 60%);

}
ResultEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 6A dark fallback colour in case the image doesn't load.
  2. Line 7The image, loaded with url().
  3. Line 8cover fills the whole banner, cropping as needed.
  4. Line 9Keep the middle of the photo in view.
  5. Line 15A soft shadow keeps the white text readable on any photo.
Example 2

cover vs contain vs repeat


.tile {

  height: 110px;

  margin: 8px 0;

  border: 2px solid #15161b;

  font: bold 14px monospace;

  background-color: #fff1c2;

  background-image: url("https://picsum.photos/id/237/160/120");

}

.cover { background-size: cover; background-position: center; }

.contain { background-size: contain; background-repeat: no-repeat; background-position: center; }

.repeat { background-size: 60px auto; }
ResultEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 7All three use the same image.
  2. Line 10Fills the box, so some of the photo is cut off.
  3. Line 11Shows the whole photo, leaving yellow gaps on either side.
  4. Line 12Small tiles repeat to fill the space (repeat is the default).
Example 3

Layering a gradient over an image

Backgrounds can stack: the first one listed is on top.


.promo {

  padding: 50px 20px;

  color: white;

  font: 800 24px sans-serif;

  text-align: center;

  background:

    linear-gradient(rgb(23 168 101 / 80%), rgb(68 103 255 / 80%)),

    url("https://picsum.photos/id/1059/800/300") center / cover;

}
ResultEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 6 to 8Two layers separated by a comma: a see-through gradient on top of a photo. More on gradients in [Shadows & Gradients]\(/css/css-shadows-gradients).

Common CSS Backgrounds Mistakes

Wrong url syntax or path

Don't

.hero { background-image: "img/sky.jpg"; }
Do

.hero { background-image: url("img/sky.jpg"); }

Images need url(). Paths are relative to the **CSS file**, not the HTML file.

An empty element with a background

Don't

.banner { background-image: url("sky.jpg"); }

/* <div class="banner"></div> has 0 height, so nothing shows */
Do

.banner {

  background-image: url("sky.jpg");

  min-height: 200px;

}

An empty element has no height, so its background is invisible. Give it content or a height.

CSS Backgrounds in Real Projects

Backgrounds in modern design

Modern sites use backgrounds to organize content without adding unnecessary markup. A travel website may use a landscape photo for its opening hero section, while a shop may use subtle colours behind pricing cards. A dashboard can use soft background colours to distinguish messages or filter areas. Decorative patterns can add personality without taking attention away from the text.

The best design usually combines appearance with practical decisions. A banner should still be readable if the image fails to load, and a photo should crop gracefully when the screen becomes narrow. Teams often pair background-size: cover with a carefully chosen background-position and a transparent gradient overlay. Simpler cards may use only background-color to avoid extra downloads and keep the interface fast.

CSS Backgrounds Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Make the photo fill the whole box and stay centred.


.cover-photo {

  background-image: \("lake.jpg");

  background-size: ;

  background-position: center;

}
Multiple choiceeasy

Which value shows the whole image without cropping?

Multiple choicemedium

What does background-repeat: no-repeat do?

Fix the bugmedium

The banner is invisible and its image tiles. Fix it: add a min-height of at least 150px, stop the repeating, and correct the image syntax.


.banner {

  background-color: #1e1b4b;

  background-image: "https://picsum.photos/id/1043/600/300";

}
ResultEdit the code, then press Run or Ctrl+Enter
Checks
  • Banner is at least 150px tall
  • Uses url() for the image
  • The image does not repeat

CSS Backgrounds Quiz

3 questions to check what you learned.

  1. Which property sets a background image?

    • background-image
    • background-src
    • image
    • bg-image
  2. In a background list of several layers, which one appears on top?

    • The last one listed
    • The largest image
    • The first one listed
    • They blend equally
  3. CSS image paths in url() are relative to…

    • the HTML file
    • the website root always
    • the browser
    • the CSS file

CSS Backgrounds Challenge

Make a photo card header

Style .card-top so that:

1\. It's 160px tall

2\. It uses https://picsum.photos/id/1080/500/300 as its background image

3\. The image covers the area and is centred, with no repeat

4\. It has a fallback background-color


.card { width: 260px; border: 2px solid #15161b; border-radius: 14px; overflow: hidden; font-family: sans-serif; }

.card p { padding: 0 12px; }
ResultEdit the code, then press Run or Ctrl+Enter
Checks
  • Header is 160px tall
  • Uses the right image
  • Covers the area
  • Centred
  • No repeat
  • Has a fallback colour