The background property in CSS allows you to control the background of HTML elements. With it, you can set colors, images, position, repeat behavior, size, and even multiple backgrounds.
1. Background Color
The simplest background property is background-color
, which sets a solid color for an element’s background.
body {
background-color: lightblue;
}
h1 {
background-color: yellow;
}
✅ This will give the entire page a light blue background, while the <h1>
has a yellow background.
2. Background Image
You can set an image as the background of an element using background-image
.
body {
background-image: url("background.jpg");
}
⚠️ If the image is smaller than the element, it will repeat by default.
3. Background Repeat
By default, background images repeat both vertically and horizontally.
You can control this with background-repeat
.
div {
background-image: url("pattern.png");
background-repeat: repeat-x; /* repeats only horizontally */
}
Options:
repeat
→ repeats both directions (default)repeat-x
→ repeats horizontallyrepeat-y
→ repeats verticallyno-repeat
→ shows the image only once
4. Background Position
Use background-position
to control where the image appears.
div {
background-image: url("logo.png");
background-repeat: no-repeat;
background-position: top right;
}
Common values:
top left
,top center
,top right
center left
,center
,center right
bottom left
,bottom center
,bottom right
- Or pixel/percentage values (
50% 20px
)
5. Background Size
The background-size
property defines how the background image is scaled.
div {
background-image: url("banner.jpg");
background-size: cover;
}
Options:
auto
→ original size (default)cover
→ fills the element, may cropcontain
→ fits inside element, maintains aspect ratio- Custom values (
100px 200px
or50% 100%
)
6. Background Attachment
This property controls whether the background scrolls with the page or stays fixed.
body {
background-image: url("bg.jpg");
background-attachment: fixed;
}
Options:
scroll
→ background scrolls with page (default)fixed
→ background stays fixedlocal
→ background scrolls with element content
7. Shorthand Background Property
Instead of writing multiple background properties, you can combine them into one shorthand property:
div {
background: url("bg.jpg") no-repeat center/cover fixed;
}
Shorthand order:background: color image repeat position/size attachment;
8. Multiple Backgrounds
CSS allows you to add multiple background images by separating them with commas.
div {
background:
url("stars.png") repeat,
url("moon.png") no-repeat center/contain,
black;
}
✅ The stars image repeats, the moon image is centered, and the black color is used as a fallback.
Summary
background-color
→ sets solid background colorbackground-image
→ sets imagebackground-repeat
→ repeat behaviorbackground-position
→ placement of backgroundbackground-size
→ scalingbackground-attachment
→ scrolling or fixed backgroundbackground
(shorthand) → combines all properties