🌱BeginnerCSS Colors and Backgrounds
CSS Backgrounds
Style element backgrounds with colors, images, gradients, and shorthand using the background property family.
Overview
CSS provides a full set of properties to control the background of any element. You can set a solid color, a repeating image, a positioned image, or a gradient or combine them.
The core background properties are:
- `background-color` fills the element with a solid color
- `background-image` sets an image or gradient as the background
- `background-repeat` controls tiling (repeat, no-repeat, repeat-x, repeat-y)
- `background-position` sets where the background starts (center, top left, 50% 50%)
- `background-size` scales the image (cover, contain, or explicit dimensions)
- `background-attachment` controls scrolling behavior (scroll, fixed, local)
All these can be written as a single shorthand property: `background`. Learning the shorthand saves a lot of typing but you must understand the individual properties first.
Key Points
- •background-color fills the element with a flat color
- •background-image: url("path.jpg") sets an image gradient functions also work here
- •background-repeat: no-repeat prevents the image from tiling
- •background-size: cover scales the image to fill the element without distortion
- •background-position: center positions the image in the element
- •The background shorthand: background: color image repeat position / size
Examples
Basic background color and image
.hero {
background-color: #1a1a2e; /* fallback if image fails */
background-image: url('hero.jpg');
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}Always set a background-color as a fallback when using background-image.
Background shorthand
/* Long form */
.card {
background-color: #f8f9fa;
background-image: url('pattern.png');
background-repeat: repeat;
background-position: top left;
}
/* Equivalent shorthand: color image repeat position */
.card {
background: #f8f9fa url('pattern.png') repeat top left;
}Contain vs Cover
/* cover: scales image to fill, may crop */
.banner {
background: url('photo.jpg') no-repeat center / cover;
}
/* contain: scales image to fit entirely, may leave gaps */
.logo-box {
background: url('logo.png') no-repeat center / contain;
}"cover" is right for hero images; "contain" is right for logos.
Common Mistakes
- Forgetting background-repeat: no-repeat images tile by default
- Omitting background-color fallback when using a background image
- Using background-size on elements with no defined height the element collapses
Note
To create a full-page hero image: set min-height: 100vh; background: url(...) no-repeat center / cover; on your hero element.
Exercises
Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4