How to Scale the Background Image to Fit in the Window With CSS

Shubham Vora Feb 15, 2024
How to Scale the Background Image to Fit in the Window With CSS

This article will teach us to scale and stretch the background image with CSS. Sometimes, we need to scale the background image according to the viewport or window size of the screen, and that is what we will do in this article.

Use the CSS background-size Property to Scale the Background Image to Fit in the Window

Programmers can use the background-size CSS property to manage the background image size. If we use the cover as a value of the CSS background-size property, we can stretch the background image according to the user’s window size.

For example, we have created the <h1> element and added some text to display into that. Also, we have set the background image using the CSS background property to the whole body.

We have passed 4 different values to the background property. The first value represents the URL of the background image.

The no-repeat shows that the background image should not be repeated and should be shown only once on the screen. The center value represents that the background image should be in the center of the screen, and the fixed represents that the background image size should be fixed, and no scroll is allowed.

Also, we have used the background-size: cover property in the CSS, which allows us to scale the image according to the body element size.

HTML Code:

<h1 class="text">This is the demo text.</h1>

CSS Code:

body {
  background: url(https://pbs.twimg.com/profile_images/959568688654553089/PuZWi9tj_400x400.jpg) no-repeat center fixed;
  background-size: cover;
}

Output:

scale background image to fit - one

In the above output image, users can see that the image is stretched, and a single image works as the background for the webpage.

We can also use 100% as a value of the CSS background-size property to fit the background image according to the viewport of the user’s screen, as shown in the example below.

CSS Code:

body {
  background: url(https://pbs.twimg.com/profile_images/959568688654553089/PuZWi9tj_400x400.jpg) no-repeat center fixed;
  background-size: 100%;
}
<h1 class="text">This is the demo text.</h1>

Output:

scale background image to fit - two

We have learned two different methods to scale the background image using CSS only in this article. Users can choose any method according to their comfortability.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - CSS Background

Related Article - CSS Image