Front-End Development 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

6 Ways to Stretch a Background Image with CSS

CSS Stretch Background Image

What Are CSS Background Images?

CSS background images are images that are placed behind the content of a container or the entire webpage. This can include anything from a simple color gradient to a complex, high-resolution photograph.

You can use CSS to control the size, position, and repeat of the background image, making it a flexible tool for creating visually attractive websites. For instance, you can use a background image to add texture to a webpage, use it as a branding element, or use it to create a visual narrative that enhances the user’s experience.

Here are a few reasons you might want to stretch or scale a background image:

  • To create a specific visual impact by having a large-scale image that conveys a message or emotion related to the content.
  • To achieve a responsive design where the background image adapts to different screen sizes or device orientations such as landscape and portrait.
  • To minimize the need for multiple images for different sections by using one large image that can be positioned and scaled as needed.

The common way to scale or stretch a background image is through the CSS property background-position. However, before manipulating the positioning, it’s important to understand the role of the background-image property, which sets one or more background images for an element.

By default, a background-image is placed at the top-left corner of an element and repeated both vertically and horizontally. We’ll explain how the background-position property works and show a few techniques for using it to effectively stretch background images, taking into consideration the initial setup provided by the background-image property.

This is part of a series of articles about CSS image

In this article:

What is the background-image Property?

The CSS background-image property plays a crucial role in enhancing the visual appeal of a webpage by allowing the assignment of one or more background images to an element.

This property ensures that the specified image is initially positioned at the top-left corner of the element and, unless otherwise defined, is repeated across both the vertical and horizontal axes to cover the entire background area.

It’s important to note that the “background” in CSS terms encompasses the entire size of the element, including any padding and border, but excluding the margin. A useful practice when working with this property is to also define a background-color. This color serves as a fallback and ensures that the element remains visually consistent and accessible in cases where the background image cannot be loaded or is unavailable, providing a seamless user experience.

Example Code:

body {
background-image: url(‘images/background.jpg’);
background-color: blue;
}

What Is the background-position Property?

The background-position property in CSS allows you to position the background image. By default, the image is placed at the top-left corner of the element. However, you can change this position to suit your design needs.

The background-position property accepts two values: one for the horizontal position (X-axis) and the other for the vertical position (Y-axis). The values can be lengths, percentages, or keywords (top, right, bottom, left, and center).

Property Values

The following keywords can be used in combination to define the position of the background image relative to the containing element:

  • left top
  • left center
  • left bottom
  • right top
  • right center
  • right bottom
  • center top
  • center center
  • center bottom

Here’s an example:

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

In this example, the image will align itself to the bottom-right corner of the body element.

4 Ways to Stretch a Background Image with background-size

Here are a few ways to use background-position to stretch or scale a background image. The sample image can be downloaded from here.

1. background-image cover property

The cover value of the background-image property scales the image as large as possible and will stretch the image to cover both the width and height of the container, even if it has to lose some parts of the image. The aspect ratio of the image is preserved, so it doesn’t get distorted.

To use the cover value, you need to set the background-size property to cover, like this:

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

In the above code, background-image sets the image you want to use as the background. background-repeat: no-repeat; ensures that the image doesn’t repeat itself. background-size: cover;stretches the image to cover the entire container.

2. background-image with 100% Width and Height

Another method to stretch a background image in CSS is by setting the width and height to 100%. Unlike the cover method, this method stretches the image to fill the entire width and height of the container. However, this can lead to distortion of the image if its aspect ratio is not the same as the container.

Here’s how you can use this method:

body {
     background-image: url('image.jpg');
     background-repeat: no-repeat;
     background-size: 100% 100%;
     min-height: 100vh;
}

In the above code, background-size: 100% 100%; sets the width and height of the image to 100%. Please note that this method might not be ideal for all situations, especially if maintaining the aspect ratio of the image is crucial.

3. background-image contain property

The background-size: contain; CSS property allows the background image to scale while maintaining its aspect ratio. The image will stretch or shrink to fit within the content box while ensuring that its proportions remain intact. It’s a useful tool to keep your image fully visible without any distortions.

Consider the following CSS code:

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

The background-size: contain; ensures that the image will cover the entire body of the webpage without distorting its aspect ratio. The image will resize according to the dimensions of the body element, and the background-repeat: no-repeat; ensures that the image doesn’t repeat.

4. background-image with Viewport Units

Another method to stretch a background image in CSS is by using viewport units. This method is particularly useful when you want the image to cover the entire viewport, regardless of its size. The viewport is the user’s visible area of a web page, and it varies with the device used to view the page.

In CSS, the viewport units are vw (viewport width) and vh (viewport height). 1vw is equal to 1% of the viewport width, and 1vh is equal to 1% of the viewport height. To stretch the background image to cover the entire viewport, you can use 100vw for width and 100vh for height.

Here’s an example:

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

In this example, background-size: 100vw 100vh; will stretch the background image to cover the entire viewport, both in width and height. The image will adjust itself as the viewport size changes.

2 Bonus CSS Background Properties

Here are two more options for stretching or scaling a background image.

Background Repeat

The background-repeat property controls if and how a background image will repeat. By default, a background image repeats both horizontally and vertically. The property accepts several values, including repeat, repeat-x, repeat-y, no-repeat, and space.

Here’s an example:

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

In this example, the image will repeat from left to right across the entire container.

Background Attachment

The background-attachment property determines if a background image will scroll with the rest of the page or stay fixed. The property accepts three values: scroll, fixed, and local.

Here’s an example:

body {
    background-image: url('image.jpg');
    background-attachment: fixed;
}

In this example, the background image will not scroll with the rest of the page. It will stay fixed at its position.

Creating Responsive Backgrounds with Cloudinary

Cloudinary is a cloud-based service that paves a smooth path towards end-to-end image and video management. It offers an array of capabilities—storage, upload, manipulation, optimization and delivery of media files. For developers striving to give their websites a facelift through striking, optimized images that adapt across devices, Cloudinary fits the bill. Let’s jump into how you can create responsive backgrounds with Cloudinary.

  • Leverage Aspect Ratio-Based Containers. You can encode the aspect ratio of an image into a CSS container. This ensures your image fits perfectly, irrespective of the dimensions of the device it’s displayed on.
  • Generate Art-Directed Images. Art direction enables developers to manually control how images behave at various breakpoints. You can define the focus area of an image, ensuring vital components are never left out in any viewport size.
  • Automate Image Responsiveness. Cloudinary lets you automate the creation of several image versions, allowing perfect display across multiple viewports. Pair these versions with ‘srcset’ and ‘sizes’ attributes in your code for opulent responsive backgrounds.
  • Optimal Format and Quality for Faster Load. Cloudinary automatically selects the best quality and format for images based on the browser and network conditions of the end-users. This ensures faster loading times without sacrificing the visual appeal.

Cloudinary acts as a bridge between stunning aesthetics and optimal website performance. So whether you are a seasoned developer aiming to revitalize your website design or a tech enthusiast making your maiden voyage into web development, add Cloudinary to your toolkit.

QUICK TIPS
Colby Fayock
Cloudinary Logo Colby Fayock

In my experience, here are tips that can help you effectively stretch background images using CSS:

  1. Use background-size: cover for balanced stretching
    When you want the background image to cover the entire container without distortion, use background-size: cover;. This preserves the aspect ratio while ensuring that the image fills the container. However, be prepared for some image cropping along the edges.
  2. Avoid distortion with background-size: contain
    If preserving the full image without cropping is important, use background-size: contain;. This will make the image fit within the container without distortion, but there might be empty spaces on the sides or top/bottom.
  3. Use background-size: 100% 100% for full stretching
    To stretch the background image across the container’s width and height, use background-size: 100% 100%;. Keep in mind this can distort the image if the aspect ratio of the container differs from the image.
  4. Leverage viewport units for full-screen backgrounds
    To cover the entire viewport, use background-size: 100vw 100vh;. This ensures the background stretches to fit the browser window exactly, making it ideal for fullscreen hero sections.
  5. Combine background-attachment: fixed for parallax effects
    Create a parallax effect by using background-attachment: fixed; along with stretched background images. This keeps the background fixed in place while the page scrolls, adding depth to the design.
  6. Use Cloudinary to automate image scaling and optimization
    Offload image optimization to Cloudinary by dynamically resizing, compressing, and serving the best format based on the user’s device and network. This reduces bandwidth usage while ensuring the images maintain visual quality across all devices.
Last updated: Aug 24, 2024