A visually appealing background can elevate your website’s design and user experience. One of the most common techniques is using a background image with CSS. Whether you’re building a landing page, a section banner, or a full-page hero, CSS makes it easy to add and control background images.
In this article, you’ll learn how to set a background image in CSS, along with best practices and customization options.
🔧 Basic Syntax: background-image
The simplest way to add a background image to an element is by using the background-image
property.
✅ Example
body {
background-image: url('background.jpg');
}
This sets background.jpg
as the background image for the entire page.
📌 Step-by-Step: How to Add a Background Image
1. Create the HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Welcome to My Website</h1>
</body>
</html>
2. Write the CSS
body {
background-image: url('images/background.jpg');
}
Ensure the path to your image is correct relative to your CSS file.
🎨 Customize the Background Image
Use the following properties to control how the background image behaves:
🔁 background-repeat
Controls whether the image repeats.
body {
background-repeat: no-repeat;
}
Values:
repeat
(default)no-repeat
repeat-x
repeat-y
🧭 background-position
Defines where the image is placed.
body {
background-position: center center;
}
Values: top left
, top center
, center
, bottom right
, or pixel/percentage values.
📏 background-size
Controls the scaling of the image.
body {
background-size: cover;
}
Common values:
cover
: Fills the entire area, may cropcontain
: Fits image within area without cropping- Custom sizes like
100px 200px
or50%
📌 background-attachment
Controls scroll behavior.
body {
background-attachment: fixed;
}
Values:
scroll
(default)fixed
: Image stays in place during scrolllocal
💡 Full Example: Background Image Hero Section
.hero {
background-image: url('images/hero.jpg');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
height: 100vh;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
<div class="hero">
<h1>Welcome to Our Site</h1>
</div>
🧠 Best Practices
- ✅ Optimize images for web to reduce loading times.
- ✅ Use
background-size: cover
for full-width sections. - ✅ Combine with fallback background color.
- ✅ Test responsiveness on different devices.
🧾 Shorthand: background
You can combine all properties into one shorthand:
body {
background: url('background.jpg') no-repeat center center / cover;
}
✅ Conclusion
Setting a background image in CSS is simple yet powerful. With just a few properties, you can fully control how your background appears and behaves. Mastering these techniques helps you create visually engaging layouts without compromising performance or accessibility.