CSS Backgrounds
CSS Backgrounds
CSS background properties are used to style the background of elements. You can set a background color, add background images, control repetition, and even combine multiple background settings using shorthand.
Background Color
The background-color property sets the background color of an element.
body {
background-color: #f6f7fb;
}
.box {
background-color: rgb(240, 248, 255);
padding: 16px;
}
Background Image
The background-image property places an image behind an element. The image is loaded from a URL.
.hero {
background-image: url("bg.jpg");
padding: 40px;
}
If the image cannot be loaded, it is a good idea to set a fallback background color.
.hero {
background-color: #e9eefc;
background-image: url("bg.jpg");
}
Background Repeat
By default, background images repeat both horizontally and vertically. You can control this behavior using background-repeat.
/* Default: repeats in both directions */
.tile {
background-image: url("pattern.png");
}
/* Do not repeat */
.no-repeat {
background-image: url("pattern.png");
background-repeat: no-repeat;
}
/* Repeat horizontally only */
.repeat-x {
background-image: url("pattern.png");
background-repeat: repeat-x;
}
/* Repeat vertically only */
.repeat-y {
background-image: url("pattern.png");
background-repeat: repeat-y;
}
Background Attachment
The background-attachment property controls whether the background image scrolls with the page or stays fixed.
/* Background scrolls with the page (default) */
.section {
background-image: url("bg.jpg");
background-attachment: scroll;
}
/* Background stays fixed while content scrolls */
.parallax {
background-image: url("bg.jpg");
background-attachment: fixed;
}
Note: Some mobile browsers handle background-attachment: fixed differently.
Background Shorthand
You can combine multiple background properties into one line using the background shorthand.
/* Long form */
.banner {
background-color: #eef3ff;
background-image: url("bg.jpg");
background-repeat: no-repeat;
background-position: center;
}
/* Shorthand */
.banner {
background: #eef3ff url("bg.jpg") no-repeat center;
}
Shorthand makes CSS shorter and easier to maintain, as long as it stays readable.
Code Challenge
Goal: Create a simple header section with a background color and a centered background image that does not repeat.
HTML:
<div class="header"> <h2>Backgrounds</h2> <p>Style your page with background properties.</p> </div>
Task:
- Set a light background color for
.header - Add a background image (
hero.jpg) - Do not repeat the image
- Center the image
- Add some padding
Try a Solution:
.header {
background: #eef3ff url("hero.jpg") no-repeat center;
padding: 40px 16px;
border-radius: 12px;
}
What’s Next?
Next, you will learn how to style borders in CSS.