CSS background properties control the visual background appearance of elements, allowing developers to set solid colors, background images, repeat patterns, attachment scrolling behaviors, and background sizes.
Background properties can be declared individually or using the background shorthand:
div {
background-color: #1e293b;
background-image: url('pattern.webp');
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
background-attachment: fixed;
}
/* Shorthand declaration */
div {
background: #1e293b url('pattern.webp') no-repeat center / cover fixed;
}
Key background properties:
background-color: Sets solid background surface color.background-image: Specifies image URL (url('...')) or gradient.background-repeat: Controls tiling (repeat, no-repeat, repeat-x, repeat-y).background-position: Sets starting alignment (center, top right, 50% 50%).background-size: Scales background images (cover, contain, 100% 100%).background-attachment: Determines whether image scrolls with the page (scroll) or remains fixed (fixed).flowchart TD
A["background-size Options"] --> B["cover (Scales to fill entire box, crops edges if needed)"]
A --> C["contain (Scales to fit entire image inside box without cropping)"]
A --> D["auto / pixel values (Displays native or fixed dimensions)"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Backgrounds Demonstration</title>
<style>
.hero-banner {
background-image: linear-gradient(rgba(15, 23, 42, 0.8), rgba(15, 23, 42, 0.8)), url('https://images.unsplash.com/photo-1518770660439-4636190af475');
background-size: cover;
background-position: center;
padding: 4rem 2rem;
border-radius: 12px;
text-align: center;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<div class="hero-banner">
<h1 style="color: #38bdf8;">Hero Banner with Gradient Overlay</h1>
<p>CSS background images scale responsively using background-size: cover.</p>
</div>
</body>
</html>
background-color: Ensures text remains readable if a background image fails to download.background-size: cover for full-width hero banners: Keeps background images scaled across mobile and desktop viewports.Create a CSS class .hero configured with a background image (hero.jpg), background-size: cover, and background-position: center!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.