Front-End Development React Optimization 101: Tips and Tricks Integrating Cloudinary with Astro Building an Image Upload Feature with JavaScript Mastering Image Alignment: Centering Images with HTML & CSS Adding Video to Your React Native App with react-native-video HTML Image Slider: Do It Yourself and 1-Step Image Gallery Widget How to Effectively Manage Digital Assets in a PHP Image Gallery Introducing Angular Image Editor: Your New Editing Too Mastering Javascript Image Annotation Mastering JavaScript Image Popup Python Video Player: 3 Free Options and a Quick Tutorial Image Recognition Machine Learning: Use Cases and Common Algorithms HTML/CSS: How to Center Images Vertically and Horizontally How to Create an Image Map Understand CSS Background Position with 4 Simple Examples Java for Image Processing: 4 Libraries You Should Know Python Video Processing: 6 Useful Libraries and a Quick Tutorial Blur Image CSS: Two Ways to Blur Images for Gorgeous Effects Designing a Video Flipping App for Android Build an App for Embedding Video Watermarks on Android Devices Change Image on Hover with HTML and CSS How to Align Images with CSS Full Page Background Image with CSS: Tutorial and 5 Automation Tips Using CSS to Scale Page Elements and a Better Way to Scale Your Images CSS Background Image: Quick Tutorial and 3 Automation Tips Featured Image: Best Practices to Feature Images on Your Website Image Gallery Websites: Tips and Tricks for a Stunning Image Gallery 6 Ways to Stretch a Background Image with CSS Auto Cropping for Images and Video: Features & Best Practices FLAC vs. WAV: 4 Key Differences and How to Choose Converting Audio to Video: A Practical Guide FLAC vs. AIFF: 5 Key Differences and How to Choose FLAC vs. MQA: 5 Key Differences and How to Choose Converting WAV Files To OGG The Ultimate Guide On Converting OGG Files To WAV Sound Choices: FLAC vs. MP3 AAC vs MP3 – The Future of Audio Files All about AIFF and how it compares to WAV and MP3 Integrating Cloudinary with Netlify Integrating Cloudinary with Svelte and SvelteKit Integrating Cloudinary with Nuxt Integrating Cloudinary with Gatsby File Upload as a Service: How It Works and 5 Leading Solutions Native Mobile App Development Creative Uses for CSS Inner Border and 3 Ways to Set a Border Integrating Cloudinary with Next.js Front-End Development: The Complete Guide

CSS Background Image: Quick Tutorial and 3 Automation Tips

css background image

The background-image property in CSS allows you to set an image as the background for any HTML element. This property can add a single image or multiple images or even create an image gradient as the background.

In CSS, you can control the position of the background image, whether or not the image should be repeated, the scrolling behavior of the image, and much more. Let’s look deeper into the syntax to understand how you can manipulate the CSS background image property to our advantage.

This is part of a series of articles about CSS Image

In this article:

Background Image Syntax in CSS

The generic syntax of the CSS background-image property is:

background-image: url('path_to_your_image');

With this syntax, the ‘url()‘ function specifies the path to the image. The image path can either be an absolute path or a relative path.

With this syntax, the ‘url()‘ function specifies the path to the image. The image path can either be an absolute path or a relative path.

The CSS background-image property also allows you to specify multiple images as backgrounds layered on top of each other. The syntax for multiple images is:

background-image: url('path_to_first_image'), url('path_to_second_image');

In this, each image is separated by a comma. The first image in the list is the topmost layer, and the rest of the images follow in the order specified.

css background image

Working with CSS Background Images

Set Background Position

The background-position property in CSS allows you to position a background image exactly where you want it. It can take two values representing the horizontal and vertical positions, respectively. For instance, background-position: center center; will position the background image in the middle of the container.

body {
  background-image: url('image.jpg');
  background-position: center center;
}

css background image

In the example above, the background image is vertically and horizontally centered. You can also use keywords like top, bottom, left, and right to position the image or specific measurements like pixels or percentages.

Background Image Repeat

The background-repeat property is one of the most commonly used properties when working with CSS background images. A background image will repeat itself horizontally and vertically by default to fill the entire container. However, this may not always be the effect you’re looking for.

body {
  background-image: url('image.jpg');
  background-repeat: no-repeat;
}

css background image

In this example, our background image isn’t repeated. Setting the background-repeat property to no-repeat prevents the image from repeating itself. Other possible values for this property include repeat-x (repeat horizontally), repeat-y (repeat vertically), or repeat (repeat in both directions).

Multiple Backgrounds

CSS allows you to add multiple background images to a single element. This can be achieved by specifying each background image in the background-image property, separated by a comma. The first image in the list will be the one closest to the viewer, and the last one will be the furthest.

body {
  background-image: url('image1.jpg'), url('image2.jpg');
  background-position: center, top;
  background-repeat: no-repeat;
}

css background image

In this example, image1.jpg will be positioned at the element’s center and will not be repeated. image2.jpg will be placed at the top and will repeat itself to fill the remaining space of the component. This feature can be useful when creating complex designs or effects.

Resizing and Attachment of Background Image

The background-size property in CSS allows you to control the size of the background image. It can take values like cover (which resizes the background image to cover the entire container), contain (which resizes the image to the largest size such that its width and height can fit inside the area), or specific dimensions.

body {
  background-image: url('image.jpg');
  background-size: cover;
}

css background image

You can also control whether a background image scrolls with the rest of the page or is fixed with the background-attachment property. For instance, background-attachment: fixed; will create a “parallax” effect where the background image does not move with the rest of the page.

Learn more in our guide to stretching background images

Background Gradients

Another feature of CSS background images is the ability to create gradients, a smooth transition between two or more colors. CSS offers three types:

  • Linear – Colors shift from one to another based on the direction (up, down, left, right, or diagonally).
  • Radial – A central point is defined, where the colors will shift outwards from that point.
  • Conic – They still share a central point, but colors are rotated around that point instead of shifting outwards.
body {
  background-image: linear-gradient(red, yellow);
}

In this example, our background image will be a gradient transitioning from red to yellow. You can also create radial gradients with the radial-gradient() function or combine multiple gradients for more complex effects.

Using Transparency

The opacity of a background image can be controlled with the background-color property in conjunction with RGBA color values. An RGBA color value includes the red, green, and blue components and an alpha component representing transparency.

body {
  background-image: url('image.jpg');
  background-color: rgba(255, 255, 255, 0.5);
}

In the example above, a white (255, 255, 255) semi-transparent (0.5) background color is applied on top of the background image. This can be useful when you want to overlay text or other content on top of a background image and ensure it’s still readable.

3 Tips for Automating Background Images

When using background images, it can be difficult to manually rescale and crop them, especially in a responsive design. With Cloudinary, you can completely automate the process and even expand images by filling in the missing details with generative AI.

Cloudinary is a cloud-based media management service with a generous free plan, simplifying working with images and videos. It allows users to perform various operations on their media files, including resizing, cropping, and optimization, through a simple URL-based system or via SDKs for all popular programming languages.

URL parameters are the key-value pairs included in the URL that instruct Cloudinary on how to manipulate and deliver the requested image or video. Using these parameters, you can easily apply a wide range of transformations to your files without needing manual intervention or additional server-side processing.

A major advantage of using Cloudinary for image resizing is that the service dynamically resizes images on the server side before they are delivered to users, solving the problems of CSS-based resizing.

Let’s see how to effortlessly resize and rescale background images with Cloudinary. In order to try out the instructions below with your own photos, sign up for a free Cloudinary account and upload the image to Cloudinary.

1. Limit Images to Specific Dimensions

To limit the size of an image to specific dimensions, we can change the crop value (c in URLs) to have a limit (c_limit).

Below is an image that’s been resized from 850 x 565 px. to 70 x 70 px. with the limit option. Due to the preserved aspect ratio, this display is 70 x 47 px.

https://res.cloudinary.com/demo/image/upload/w_70,h_70,c_limit/cashew_chicken.jpg

css background image

Learn more in the Cloudinary Cookbook

2. Crop Images With Auto Gravity

To focus on specific details—faces, objects, color contrasts—while resizing images, we can crop the images with Cloudinary’s intelligent auto-gravity features. The parameter to set is gravity (g in URLs), which offers an auto value (g_auto) that intelligently crops according to your image’s content.

Cloudinary automatically crops images with content-aware, AI-based features by selecting faces, individual features, or areas of interest. Look at how Cloudinary uses the g_auto setting to crop the most interesting area, as determined by AI:

css background image

Another example of avoiding irrelevant objects instead of the product in product images taking center stage is defining the product as the focus. The picture on the right below has the backpack in focus.

This code uses g_auto:classic

https://res.cloudinary.com/demo/image/upload/c_thumb,g_auto:classic,h_175,w_175/v1551428220/veducate/spencer-backman-482079-unsplash.jpg

css background image

This code uses g_auto:backpack to focus on the backpack:

https://res.cloudinary.com/demo/image/upload/c_thumb,g_auto:backpack,h_175,w_175/v1551428220/veducate/spencer-backman-482079-unsplash.jpg

css background image

Learn more about gravity-based cropping in our tutorial

3. Expand Images with AI-Powered Generative Fill

Generative Fill works with Cloudinary’s padding crop modes and leverages the new gen_fill option for backgrounds (b_gen_fill for URLs). Combining these options allows users to achieve a visually pleasing fill that seamlessly matches the original image. You can even add a natural language prompt to the gen_fill command to specify what the generated background should contain.

Let’s see an example of generative fill. Here is an original image with a width of 600 and a height of 900:

css background image

Original image, 600×900

Here is how we use c_pad to resize the image while maintaining aspect ratio and visibility of the original. Then, Cloudinary adds in new areas by using their generative fill. This code pads the original to a 1:1 aspect ratio.

https://res.cloudinary.com/demo/image/upload/b_gen_fill,c_pad,ar_1:1/v1687525630/ai/woman_model.jpg

css background image

Here, we can use c_lpad to scale down the image with padding if it is larger than the specified width/height limit, maintaining aspect ratio and visibility. The new areas will be generated around the scaled image as needed. Here, we’ve created a 400×800 image from the original – the original is shrunk to fit, and new imagery is inserted, including feet!

https://res.cloudinary.com/demo/image/upload/c_lpad,h_800,w_400,b_gen_fill/v1687525630/ai/woman_model.jpg

css background image

For more information on generative fill, check out the documentation or try the demo.

Sign up for a free Cloudinary account and resize images automatically with these features and more.

QUICK TIPS
Colby Fayock
Cloudinary Logo Colby Fayock

In my experience, here are tips that can help you better manage background images using CSS and automation tools:

  1. Use background-size: cover for full-screen background images
    To ensure your background image always covers the entire screen or container without distortion, use background-size: cover;. This makes sure the image scales to fit, but beware it might crop some parts, so choose images where this won’t matter.
  2. Leverage background-position for responsive alignment
    Use background-position strategically to focus on the most important parts of the image. For example, background-position: center; works for most cases, but for images with key elements in specific areas, adjust accordingly (e.g., top left, bottom center).
  3. Combine background-attachment: fixed for parallax effects
    To create a more engaging user experience, apply background-attachment: fixed; to keep the background in place while users scroll through the content. This creates a subtle parallax effect and adds depth to the page design.
  4. Optimize image loading with lazy loading
    Implement lazy loading for background images, especially for large images that don’t appear immediately when the page loads. This will improve page speed and prevent unnecessary bandwidth consumption, boosting performance and user experience.
  5. Generate responsive background images automatically
    Use Cloudinary to automate image resizing for different devices. By dynamically resizing the background images server-side, you can serve the most optimized version for each screen resolution, improving load times without manual intervention.
  6. Crop images using auto-gravity for better focus
    If the focal point of the image is important (e.g., a product or a person), use Cloudinary’s g_auto feature to automatically crop the image around the most significant area. This ensures the focus remains clear on all screen sizes.
  7. Apply AI-powered generative fill for seamless padding
    For awkwardly cropped background images, Cloudinary’s generative fill can automatically extend images by adding AI-generated padding. This can ensure your background images fit perfectly while keeping the design seamless and aesthetically pleasing.
  8. Use multiple backgrounds for layered effects
    Combine multiple background images for a richer design. Using CSS, you can layer backgrounds (e.g., an image and a gradient) to add depth and detail, which is useful for creating visually complex, yet performant, designs.
  9. Consider performance and compression
    Always optimize background images with compression tools or services like Cloudinary’s q_auto to balance quality and performance. Compressed images load faster, improving both user experience and SEO ranking.
  10. Test on multiple screen sizes and resolutions
    Ensure your background images are responsive and look sharp across devices by using tools like Cloudinary’s image-set() for delivering different resolutions (1x, 2x, 3x). This ensures high-DPI screens receive high-quality images, and lower resolution screens get optimized versions.
Last updated: Aug 24, 2024