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:
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:
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.
Related Article - CSS Background
- How to Have Gradient Background in CSS
- Stretchable Background Image Using CSS
- How to Create Background Image Gradient With CSS
- Transparent Background Color in CSS
- How to Center Background Images in CSS