Background layers and positioning
Definition and purpose
CSS backgrounds paint color and image layers behind content. Multiple images are stacked in list order with the first image closest to the viewer.
Position a decorative layer
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> #a { height: 80px; background-image: linear-gradient(blue, blue); background-size: 20px 20px; background-position: right top; background-repeat: no-repeat; background-color: white; } </style> </head> <body> <div id="a" aria-hidden="true"></div> </body></html>A blue square is positioned at the top right. The gradient is an image value; gradients are explained next.
Syntax and mental model
background-image, background-size, background-position and background-repeat control distinct aspects. A comma separates layers; shorter lists repeat to match the image count. The background color lies below all images. cover fills the area with possible cropping; contain fits the whole image.
Two layers
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> #a { height: 80px; background-image: linear-gradient(red, red), linear-gradient(blue, blue); background-size: 20px 20px, 100% 100%; background-repeat: no-repeat; } </style> </head> <body> <div id="a" aria-hidden="true"></div> </body></html>The small red layer paints over the blue one.
Common mistakes
Background images are decorative, not substitutes for meaningful images and alternative text. The background shorthand resets omitted background longhands.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Color mixing and relative colors, Aspect ratio and replaced elements. Next lesson: Gradients.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Background layers and positioning — knowledge check
Five questions on background layers and positioning.
Which image layer paints on top?
Which size fills an area and may crop?
Which prevents tiling?
Where is the background color painted?
What can the background shorthand do?