CSS
CSS – How to Set a Background Image
Adding a background image is one of the most common styling tasks in web design. Whether you’re creating a hero section, a stylish banner, or a textured background, CSS makes it easy to apply images behind your content.
In this article, you’ll learn how to set a background image using CSS, customize it for different screen sizes, and avoid common pitfalls.
🖼️ Basic Syntax
To add a background image using CSS, use the background-image
property.
Example:
.hero-section {
background-image: url('images/bg.jpg');
}
This sets the background image for the .hero-section
element.
Full Example:
<div class="hero-section">
<h1>Welcome to My Website</h1>
</div>
.hero-section {
background-image: url('images/bg.jpg');
height: 400px;
color: white;
}
🔧 Controlling the Background Image
CSS provides several additional properties to customize the background behavior:
1. background-size
Controls how the image is scaled.
cover
: scales the image to cover the entire elementcontain
: scales the image to fit within the element
.hero-section {
background-size: cover;
}
2. background-position
Controls where the image is placed inside the element.
.hero-section {
background-position: center center;
}
Other common values:top left
, top center
, bottom right
, etc.
3. background-repeat
By default, background images repeat. To prevent tiling:
.hero-section {
background-repeat: no-repeat;
}
4. background-attachment
Defines whether the background scrolls with the page.
.hero-section {
background-attachment: fixed;
}
Use with caution, as fixed
backgrounds can behave differently on mobile browsers.
🧩 Combined Shortcut: background
You can set all the background properties in a single line:
.hero-section {
background: url('images/bg.jpg') no-repeat center center / cover;
}
Breakdown:
url('images/bg.jpg')
= image sourceno-repeat
= don’t tile the imagecenter center
= position/ cover
= size
📱 Responsive Background Images
Use background-size: cover
for most responsive designs:
.banner {
background-image: url('images/responsive.jpg');
background-size: cover;
background-position: center;
height: 100vh;
}
This ensures your background image fills the viewport nicely on all devices.
📝 Summary
Property | Purpose |
---|---|
background-image | Set the image URL |
background-size | Scale image (cover , contain ) |
background-position | Align image within container |
background-repeat | Prevent tiling (no-repeat ) |
background-attachment | Scroll behavior (fixed , scroll ) |
✅ Conclusion
Using CSS to set a background image is straightforward, yet powerful. With properties like background-size
, position
, and repeat
, you can fully control how the image appears and behaves in your layout.
Whether you’re designing a full-screen landing page or simply adding a visual accent, CSS background images help bring your web designs to life.