How to add and customize CSS background image
Last edited:
Trust Jamin OkpukoroTo add a background image in CSS, set the background-image property on an element, point it to your image URL, then control how it displays with background-size, background-position, and background-repeat:
.hero {
background-image: url('hero-bg.jpg');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
height: 100vh;
}This gives you a full-screen background image that scales cleanly on any screen size.
CSS background-image set on a full-screen hero section using background-size: coverIn this guide, youโll learn how to add a background image in CSS, make it responsive, best practices to follow, and how you can optimize background images with Uploadcare.
What are CSS background images?
The background-image property inย CSS allows you toย decorate HTML elements with visuals like images, graphics, and patterns without bloating your markup. You can use image formats like AVIF, WebP, JPEG, PNG, SVG, orย even gradients.
You can use the CSS background-image property toย set anย image asย the background ofย anย element,
such asย a div, section, orย even the entire body ofย your webpage.
css-selector {
background-image: url('path/to/image.jpg');
}Where css-selector isย the HTML element you want toย style, background-image isย the CSS property being applied,
and url() isย aย function that specifies the path toย the image file.
Note that the image path can beย relative (located inย the same project asย your HTMLย code) orย absolute (hosted somewhere else with anย http:// orย https:// address). You can also use data URIs for smaller images.
When and why should you use CSS background images?
CSS background images let you add decorative visuals toย elements without cluttering your HTML. Theyโre ideal when the image doesnโt carry semantic meaning.
The image isย usually displayed behind the elementโs content, thus enhancing the design ofย your site while keeping your markup clean and semantic.
Ifย youโd like aย background for aย specific element, like aย section orย aย div, without using solid colors, aย CSS background image isย the right choice. Itย can help make your design more visually appealing.
Itย can also improve download speed and performance when using CSS Sprites, allowing you toย combine multiple images into aย single file. This reduces the number ofย HTTP requests the browser makes, leading toย faster load times.
Use them when:
- The image isย purely decorative
- You need toย create aย specific layout orย design effect
- You want toย apply effects like parallax scrolling orย fixed backgrounds
- You want toย use CSS properties toย control the position, size, and how the image isย displayed
Using CSS background image, like for aย hero banner, isย aย great use case. The visual inย this case doesnโt convey semantic meaning.
Inย other cases, where semantic meaning isย important,
like aย company logo, an <img> isย more appropriate and better tag for accessibility reasons.
How toย add aย background image inย CSS
Letโs start with the basics.
Here isย anย example ofย how toย set the background image inย CSS for a div element with a .hero class:
.hero {
background-image: url('hero-bg.jpeg');
}Itย sets the image asย the background for elements with the .hero class.
Doย note that the element should have aย visible height either through its own styles orย its content for the background image toย appear asย expected.
Inย many cases, setting anย explicit height, min-height,
orย using padding onย child elements ensures the image displays correctly.
Otherwise, the element might collapse toย zero height,
especially ifย itโs empty, and the background wonโt beย visible atย all.
.hero {
background-image: url('hero-bg.jpeg');
height: 100vh;
}The will render the element like this:
Background image tiled and repeating across a hero div without background-sizeAlthough the above example isย aย good start, itย does not look very good onย smaller screens, and the image isย repeated. Letโs explore some CSS properties you can use toย customize the background image.
Essential CSS background properties
You can apply some CSS properties toย control your background images fully. Hereโs aย quick rundown ofย aย few ofย them:
background-image property
The background-image property isย the first step inย adding aย background image.
Itย sets the image toย beย used asย the background ofย anย element.
.hero {
background-image: url('hero-bg.jpeg');
}You can also add multiple images byย separating them with commas:
.hero {
background-image:url('star.png'), url('hero-bg.jpeg');
}This will stack the images onย top ofย each other, with the first image onย top.
Two stacked CSS background images, a star layered over a hero photoOrย use aย gradient with anย image:
.hero {
background-image: linear-gradient(to right, rgba(41, 102, 201, 0.8), rgba(254, 180, 123, 0.8)), url('hero-bg.jpeg');
}
CSS background image with a linear-gradient overlay tinting the photoSome supported images for this property include:
- JPEG: Common format for photos and complex images
- PNG: Good for images with transparency
- SVG: Scalable vector graphics, great for logos and icons
- WebP: Modern format that provides better compression and quality
- AVIF: Aย newer format that offers even better compression and quality than WebP
- GIF: Good for simple animations, but not ideal for static images
For better performance and quality, use WebP orย AVIF. They are smaller and provide better quality than traditional formats like JPEG and PNG.
background-position property
The background-position property controls where the image appears inside the element.
You can use values (top, bottom, left, right, center), percentages,
orย even exact unit measurements like px or rem.
.hero {
background-image: url('hero-bg.jpeg');
background-position: center;
height: 100vh;
}The above code will center the image inย the element.
Background image centered in the element with background-position: centerYou can also use percentages toย position the image:
.hero {
background-image: url('hero-bg.jpeg');
background-position: 50% 50%;
height: 100vh;
}Using 50% 50% centers the image both horizontally and verticallyย โ specifically, the center ofย the image aligns with the center ofย the container.
Ifย you use, say, 20% 20%, the point thatโs 20% across andย 20% down the background image will align with the same relative point inย the container.
For aย list ofย all the possible values, check out the MDN documentation.
background-repeat property
Asย you must have noticed, the background image inย the previous examples isย repeated multiple times.
This isย because the default value for the background-repeat property isย set to repeat when the image isย smaller than the element.
That means the image will repeat horizontally and vertically toย fill the entire element.
The background-repeat property controls ifย and how the image repeats.
Toย control the repetition, you can use values like no-repeat, repeat-x, repeat-y, round or space.
Letโs say you want toย display the image only once; you can set the background-repeat property to no-repeat:
.hero {
background-image: url('hero-bg.jpeg');
background-repeat: no-repeat;
height: 100vh;
}The image appears just once, without repetition.
Background image shown once using background-repeat: no-repeatNotice that the image isย centered inย the element and does not repeat. Ideally, the image should toย beย aย full-screen background image, but itย does not fill the entire element because itย isย smaller than the element itself.
Toย fix this, letโs use the next property, background-size.
background-size property
The background-size property controls how the image scales within the element.
You can use values like cover, contain, orย specify the imageโs dimensions.
Popular values include:
cover: fills the element while maintaining the aspect ratiocontain: makes sure the whole image isย visible100% 100%: stretches toย fit both width and height (can distort)
.hero {
background-image: url('hero-bg.jpeg');
background-size: cover;
height: 100vh;
}Ifย youโre wondering how toย make the background image fit full screen inย CSS,
the background-size: cover property isย your go-to for full-bleed visuals
Background image filling the full element with background-size: coverbackground-attachment property
The background-attachment property controls how the background image behaves when you scroll the page.
Have you ever visited aย site with aย parallax effect, where the background image ofย the content stays moves atย aย different speed
than the content while the scrolling?
Thatโs the magic of background-attachment.
You can use the following values for the background-attachment property:
scroll: the default value, the background isย fixed relative toย the element and isย attached toย the elementโs bordersfixed: the background stays fixed relative toย the viewport while the content scrolls creating aย parallax effectlocal: the background isย fixed relative toย the element content, soย itย scrolls with the content ofย the element
.hero {
background-image: url('hero-bg.jpeg');
background-attachment: fixed;
height: 100vh;
}Combining properties
Combining all these properties can create stunning effects. For example, you can create aย full-screen background image with aย parallax effect like this:
.hero {
background-image: url('hero-bg.jpeg');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
height: 100vh;
}Creates aย full-screen background image that stays fixed while the content scrolls, creating aย parallax effect.
How toย make background images responsive
Responsiveness isย important when dealing with background images, asย you want your images toย look great onย all devices, from desktops toย smartphones.
Here are some tips toย make your background images responsive.
Use background-size: cover
The cover value for background-size will ensure the image covers the entire element while maintaining its aspect ratio.
Itย might crop the image aย bit, but itโs aย good trade-off for responsiveness.
For large screens, you can use background-size: cover toย ensure the image fills the entire element,
and for smaller screens, you can use background-size: contain toย ensure the entire image isย visible
while maintaining its aspect ratio.
When combined with background-position: center, this keeps the focal point ofย the image inย the center,
making itย look good onย all screen sizes, especially onย mobile devices.
Another option isย toย specify the size inย percentages orย viewport units (like vw and vh) toย make itย more flexible.
For example:
.hero {
background-image: url('hero-bg.jpeg');
background-size: 100% 100%;
height: 100vh;
}The image stretches toย fill the entire element, but itย may distort the image ifย the elementโs aspect ratio isย different from that ofย the image.
Use media queries
Ifย you want toย change the background image based onย the screen size, you can use media queries toย swap inย different images orย adjust the size ofย the image.
Media queries are CSS techniques that allow you toย apply styles based onย the screen size orย device type. This isย particularly useful for responsive design.
Ifย the userโs device meets the conditions specified, the styles inside the media query will beย applied, allowing you toย create aย responsive design that adapts toย different screen sizes and devices.
For example, you can set aย different background image for mobile devices like this:
@media (max-width: 768px) {
.hero {
background-image: url('hero-mobile.jpg');
background-size: contain;
}
}With this change, the background image will beย swapped with hero-mobile.jpg when the screen width is 768px orย smaller.
For even more control across screen sizes, you can pair your background images with image-set().
Learn more inย our guideย on responsive images with image-set.
Optimizing background images for performance
While background images can enhance your design, they can also slow down your site ifย not optimized properly. Aย 2ย MB background image can lead toย aย sluggish experience, especially onย mobile devices.
Here are some tips toย optimize your background images for performance.
Use the right format
Choose the right image format for your background images, asย this can drastically reduce the load time ofย your web page. Consider using WebP orย AVIF for better compression and quality for modern browsers. These formats are smaller than older formats like JPEG and PNG but maintaining high quality.
Compress your images
Before using anย image, use image compression tools toย reduce its file size without sacrificing quality. Tools like Squoosh, TinyPNG, orย ImageOptim can help you achieve this. You can also use Uploadcareโs built-in optimization features toย automatically compress and optimize your images onย the fly.
Use lazy loading
Lazy loading isย aย technique that defers the loading ofย images until they are inย the viewport.
This can significantly improve the initial load time ofย your web page.
Although native lazy loading applies to <img> tags,
you can mimic itย for background images using Intersection Observers inย JavaScript
orย byย dynamically applying classes toย load images only when they are inย the viewport.
const lazyLoadBackgrounds = () => {
const lazyBackgrounds = document.querySelectorAll('.lazy-bg');
const options = {
root: null,
rootMargin: '0px',
threshold: 0.1
};
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('loaded');
observer.unobserve(entry.target);
}
});
}, options);
lazyBackgrounds.forEach(bg => {
observer.observe(bg);
});
};
document.addEventListener('DOMContentLoaded', lazyLoadBackgrounds);The code above uses the Intersection Observer API toย detect when elements with the class .lazy-bg are inย the viewport
and adds the class .loaded toย them.
.lazy-bg {
/* Initially no background image */
background-image: none;
}
.loaded {
/* Add the background image when loaded */
background-image: url('hero-bg.jpeg');
}This will initially set the background image toย none, and when the element isย inย the viewport, itย will add the background image.
Use CSS sprites
Ifย you have multiple small images (like icons), consider using CSS sprites. This technique combines multiple images into aย single image file, reducing the browserโs HTTP requests. While itโs anย older technique, itย can still beย relevant for specific use cases where you want toย use multiple small images for the background.
Use aย CDN
Ifย youโre serving large background images, consider using aย Content Delivery Network (CDN) toย serve them. CDNs cache images onย servers around the world, reducing the distance between the user and the server, resulting inย faster load times. Uploadcare offers aย CDN that automatically optimizes and serves your images.
Toย learn more about optimizing images for performance, check out our guideย on optimizing images for website performance.
Using Uploadcare toย serve optimized background images
Weย would beย remiss not toย mention aย smoother way toย manage and deliver optimized background images.
Uploadcare allows storing, optimizing, and serving your images fromย a lightning-fast CDN. This means faster load times and automatic format conversion ( WebP and AVIF).
Toย use Uploadcare for your background images, sign upย and upload your images toย Uploadcare. Then, use the provided file URL inย your CSS:
.hero {
background-image: url('https://6ca2u7ybx5.ucarecd.net/YOUR_IMAGE_UUID/-/preview/1600x900/');
}But Uploadcare isย more than just aย CDN provider, itย offers aย full media solution such asย a File Uploader and APIs for optimizing and delivery your images toย your user anywhere for example, its URL-based API allows you resize, crop, and convert your image onย the flyย โ noย editing required
Transformations are URL-based tools that let you resize, crop, and convert your image onย the flyย โ noย editing required
Adding the transformation -/preview/1600ร900/ toย the URL will resize the image toย 1600ร900ย pixels.
You can also use transformations like -/format/webp/ or /-/crop/ toย manipulate anย image onย the fly.
Using this dynamic transformation, you can easily create responsive background images without uploading multiple versions.
@media (max-width: 768px) {
.hero {
background-image: url('https://6ca2u7ybx5.ucarecd.net/YOUR_IMAGE_UUID/-/preview/800x450/');
background-size: contain;
}
}Want toย fine-tune how your background images appear? Check out our guideย on how toย crop images inย CSS using Uploadcareโs transformation tools.
Uploadcare also provides a uc-img component that lets you easily add images toย your HTML with built-in optimizations.
This component automatically handles lazy loading and responsive images and can also serve optimized background images.
Toย use the uc-img component, import the uc-img component library into your page:
<script src="https://cdn.jsdelivr.net/npm/@uploadcare/file-uploader@v1/web/uc-img.min.js" type="module"></script>uc-img {
--uc-img-pubkey: 'YOUR_PUBLIC_KEY';
}Where YOUR_PUBLIC_KEY isย your Uploadcare public key from your Uploadcare project.
Then, you can use the uc-img component inย your HTML like this:
<uc-img is-background-for="#target" src="SOURCE_IMAGE_PATH"></uc-img>Where is-background-for isย anย attribute that targets the CSS selector ofย the element you want toย apply the background image,
and SOURCE_IMAGE_PATH isย the path toย your image.
Toย see this inย action, hereโs anย example ofย how toย use the uc-img component toย create aย responsive background image:
<div id="hero">
<div>
<h1>Hello World</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deleniti doloremque perferendis laborum possimus
distinctio libero. Odio iste laboriosam repellendus molestias minima reiciendis facilis voluptate nisi et
molestiae esse, eligendi quia.
</p>
</div>
<uc-img
is-background-for="#hero"
src="https://6ca2u7ybx5.ucarecd.net/64e2c9da-0835-4d04-9d34-a5a4f5ad0421/photo1470770841072f978cf4d019e/"
></uc-img>
</div>Inย your CSS, you can set the background properties like this:
#hero {
height: 100vh;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
}Conclusion
Adding and customizing CSS background images doesnโt need toย beย complicated. With the right mix ofย CSS background properties, responsive techniques, and performance best practices, and using anย optimization tool like Uploadcare, you can create stunning visuals without sacrificing speed orย usability.
Ready toย serve optimized background images onย your websites? Try out Uploadcare today
Happy styling!