Topic 10 of 30
Backgrounds
Overview
CSS background properties control the color, image, size, position, and repeat behavior of element backgrounds. Modern CSS allows multiple backgrounds and gradients, enabling complex visual effects without images.
Syntax
css
/* Color */
background-color: #1a1a1a;
/* Image */
background-image: url('/hero.jpg');
background-size: cover; /* cover | contain | 100% */
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed; /* parallax effect */
/* Gradients */
background: linear-gradient(135deg, #0f0f0f 0%, #1a1a1a 100%);
background: radial-gradient(circle at top right, #FFD700 0%, transparent 60%);
/* Shorthand */
background: linear-gradient(135deg, #000, #1a1a1a) center/cover no-repeat;Common Pitfalls
- background-size: cover scales the image to cover the container, potentially cropping it — this is usually desired for heroes.
- Multiple backgrounds are listed comma-separated; the first one is on top.
- Interview tip: For performance, prefer CSS gradients over background images where possible — they don't require network requests.
Real-World Example
A hero section with a gradient overlay on a background image:
example
css
.hero {
background:
linear-gradient(
to bottom,
rgba(0, 0, 0, 0.7) 0%,
rgba(0, 0, 0, 0.4) 100%
),
url('/images/bangalore-skyline.jpg') center/cover no-repeat;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
/* Animated gradient button */
.btn-gradient {
background: linear-gradient(90deg, #FFD700, #FFA500, #FFD700);
background-size: 200%;
transition: background-position 0.4s ease;
}
.btn-gradient:hover {
background-position: right center;
}