Background images serve a variety of purposes in web development. From enhancing a website’s visual appeal, to storytelling, branding and setting moods, background images can significantly improve your website accessibility and give you a competitive edge.
However, implementing background images effectively requires careful consideration of performance, compatibility, and accessibility; and this is where most developers get it wrong.
In this article, we’ll explore five best practices for using HTML background images to ensure your website is both visually compelling and performant. Let’s dive in!
In this article:
- 1. Choose the Right Image, Image Format, and Compression Settings
- 2. Use CSS Background Properties for Optimal Control
- 3. Implement Responsive Background Images with Cloudinary
- 4. Optimize Loading Performance with Lazy Loading and Fallbacks
- 5. Maintain Accessibility and Readability with Strategic Design
1. Choose the Right Image, Image Format, and Compression Settings
Choosing the appropriate image, image format, and applying the correct compression settings are one of the foundations for using background images effectively. Every background image should serve a clear purpose and complement the message and tone of the page it’s being used on.
For example, imagine visiting the homepage of a fitness website that aims to motivate users to adopt a healthy lifestyle. A vibrant, high-energy image can immediately inspire action. On the other hand, a dull or unrelated background image can send mixed signals and fail to engage visitors.
Similarly, different image formats have their unique strengths and serve distinct purposes, and by using the best image format, you can make informed decisions that will help you achieve a balance between visual quality and performance.
Here are some of the most common image formats and when it’s best to use each.
- WebP: Although relatively new, WebP is the most ideal format for modern browsers. One of the major benefits of WebP is that it typically produces smaller file sizes compared to JPEG or PNG while maintaining excellent image quality.
- JPEG: JPEG is an older format but suitable for complex, colorful images (like photographs), and a great choice when wide browser support is needed.
- PNG: PNG is best for simple images that require transparency, but generally not recommended for large backgrounds due to file size.
- SVG: Great for patterned backgrounds or icons that need to scale without loss of quality.
Image compression is an image optimization technique that improves websites performance by reducing page load times, bandwidth usage, and storage costs. You can use compression tools like Cloudinary Image to optimize images automatically, significantly reducing file sizes while preserving quality.
2. Use CSS Background Properties for Optimal Control
Rather than embedding background images directly in HTML using the <img>
tag, background images should be applied via CSS. CSS provides useful properties for managing background images, offering greater flexibility and control compared to inline HTML attributes. These properties are:
background-image
: This property is the go-to for setting the image URL that will serve as the background for an element. You simply provide the path to your image file, likeurl('hero-image.webp')
:
.hero-section { background-image: url('hero-image.webp'); }
background-size
: This controls how your background image scales within its parent container. Its acceptable values include:cover
(use this to scale the image to cover the entire element and if cropping is necessary);contain
(use this to fit the image within the element without cropping); or specific dimensions (e.g.,50%
,200px 100px
) to precisely control the width and height of the background image.background-position
: This property defines where the background image is placed within its container. You can use keywords likecenter
,top
,bottom
,left
,right
, or combinations liketop right
. Alternatively, you can use numerical values (e.g.,50% 50%
for center, or20px 30px
to position it from the top-left corner).
.hero-section { background-image: url('hero-image.webp'); background-position: center; } /* OR */ .hero-section { background-image: url('hero-image.webp'); background-position: bottom left; } /* OR */ .hero-section { background-image: url('hero-image.webp'); background-position: right 5% bottom 15px; }
background-repeat
: This property determines whether and how the background image repeats. By default, images repeat both horizontally and vertically (repeat
). However, you can specifyno-repeat
to show the image only once.repeat-x
will make the image repeat only horizontally, whilerepeat-y
will repeat it only vertically.background-attachment
: This controls how the background image behaves when the user scrolls. Its acceptable values include,scroll
,fixed
, andlocal
.
Using CSS to add background images to your web pages allows for a more streamlined and flexible approach than using HTML attributes. For example, you can implement advanced background image techniques, such as adding multiple background images with CSS, as follows:
.hero-section { background: url('overlay.png'), url('main-image.webp'); background-size: cover, cover; background-position: center, center; }
3. Implement Responsive Background Images with Cloudinary
One of the most common problems developers encounter with images on the web is ensuring their responsiveness across devices. Responsive image design is important for delivering a consistent experience across devices as a one-size-fits-all background image can either waste bandwidth or appear pixelated. A cloud-based media management solution like Cloudinary makes it easy to deliver responsive images tailored to each user’s device.
Cloudinary can automatically resize images based on device resolution by using its URL-based transformations or any of its programmable SDKs, depending on your use cases:
.hero-section { background-image: url('https://res.cloudinary.com/your-account/image/upload/w_800/hero-image.webp'); }
You can also combine Cloudinary with CSS media queries to serve different images for different screen sizes:
.hero-section { background-image: url('https://res.cloudinary.com/your-account/image/upload/w_400/hero-image.webp'); } @media (min-width: 768px) { .hero-section { background-image: url('https://res.cloudinary.com/your-account/image/upload/w_1200/hero-image.webp'); } }
By combining CSS with Cloudinary to implement background images, you minimize overhead while gaining greater control over responsiveness, performance, and visual quality.
4. Optimize Loading Performance with Lazy Loading and Fallbacks
Background images can be heavy during the initial page load time, especially for users on slower connections. Lazy loading allows you to defer the loading of images that don’t appear in the initial viewport until they are needed, reducing initial load time and bandwidth usage.
Since browsers don’t natively support lazy loading for CSS background images in HTML elements other than img
tags, you can implement it using JavaScript and the Intersection Observer API. To do so, apply the lazy-loading
class and data attribute to the element in HTML:
<div class="hero-section lazy-background" data-bg="/images/hero-image.webp"></div>
Then in JavaScript:
document.addEventListener('DOMContentLoaded', () => { const lazyBackgrounds = document.querySelectorAll('.lazy-background'); const observer = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { const element = entry.target; element.style.backgroundImage = `url(${element.dataset.bg})`; observer.unobserve(element); } }); }); lazyBackgrounds.forEach(bg => observer.observe(bg)); });
Alternatively, you can use libraries like lozad.js
or yall.js
(Yet Another Lazy Loader) to simplify the implementation of lazy loading for CSS background images.
These best practices will improve the performance of background images in your websites and applications:
- For background images that appear in the initial viewport when the user lands on the web page, use
<link rel="preload">
to prioritize their loading:
<link rel="preload" as="image" href="hero-image.webp">
- Serve images through a content delivery network (CDN) and asset management platform like Cloudinary to reduce latency. CDNs deliver content from servers geographically closer to the user, thereby speeding up load times.
- Always provide fallback styles or low-resolution placeholders (e.g., blurred versions or gradient backgrounds) for a smooth and continuous visual experience during image loading.
5. Maintain Accessibility and Readability with Strategic Design
If your high-quality background images compromise accessibility or readability, then you haven’t truly achieved an ideal background design. Many developers use text overlays on background images to convey key messages and capture a reader’s attention. However, balancing visual appeal and accessibility is often a significant challenge, particularly for developers new to accessible design.
To improve the accessibility and readability of your background images, consider the following best practices:
- Ensure there’s sufficient contrast between text and the background image.
- To further improve text readability, consider adding a semi-transparent overlay between the text and the background image, or applying a subtle text shadow. These techniques help to visually separate the text from the image.
- Choose background images with minimal visual noise to prevent text from blending into the background and becoming difficult to read.
- Always specify a solid background color as a fallback. This ensures that content remains readable for cases where the image fails to load.
Bring It All Together with a Great Background Image
Background images are a powerful visual tool, but without thoughtful implementation, they can hinder performance, accessibility, and design integrity. By choosing the right formats, leveraging CSS control, using responsive delivery via platforms like Cloudinary, optimizing for performance, and designing with accessibility in mind, you can ensure your background images enhance the user experience rather than compromise it.
Boost your website’s speed and user experience by optimizing your media assets with Cloudinary. Sign up for free today!