CSS Backgrounds
CSS backgrounds are used to control the background appearance of HTML elements. They allow you to add colors, images, gradients, and control how backgrounds are positioned and repeated.
Background Color
The background-color property sets the background color of an element.
body {
background-color: #f0f0f0;
}
Background Image
The background-image property is used to add an image as a background.
div {
background-image: url("image.jpg");
}
Background Repeat
By default, background images repeat both horizontally and vertically.
The background-repeat property controls this behavior.
.container {
background-repeat: no-repeat;
}
Background Position
The background-position property defines the starting position
of a background image.
.section {
background-position: center;
}
Background Size
The background-size property controls the size of the background image.
.hero {
background-size: cover;
}
Background Attachment
The background-attachment property specifies
whether the background image scrolls with the page or remains fixed.
.banner {
background-attachment: fixed;
}
Shorthand Background Property
Multiple background properties can be written using a single shorthand property.
.box {
background: #ffffff url("bg.jpg") no-repeat center / cover;
}
Multiple Backgrounds
CSS allows you to apply multiple background images to a single element.
.card {
background-image: url("layer1.png"), url("layer2.png");
}
Background Gradients
CSS gradients allow smooth transitions between two or more colors without using images.
.gradient {
background: linear-gradient(to right, #00c6ff, #0072ff);
}
Radial Gradient
Radial gradients spread outward from a center point.
.circle {
background: radial-gradient(circle, #ffcc00, #ff6600);
}
Best Practices for Backgrounds
- Use optimized images to improve performance
- Ensure text readability over backgrounds
- Avoid overusing fixed backgrounds
- Use gradients for modern designs
Common Mistakes with Backgrounds
- Large unoptimized background images
- Poor contrast between text and background
- Incorrect background positioning
background-size: cover;
for full-width responsive background images.