LAST UPDATED: AUGUST 5, 2021
How to Stretch and Scale an Image in the Background with CSS
Answer: Using background-size
property
When you add an image to the background. The image should completely fill the background area. This can be done using CSS. In this tutorial, we will learn to stretch and scale an image in the background with CSS.
The background-size
property is used to define the size of the image used in the background. It resizes the background image by specifying the height and width of the image so that the image completely covers the background area. There are two special values used by the background-size property.
contain
- The contain
value specifies that the background image should be scaled so that each side is as large as possible and does not exceed the size of the container.
cover
- The cover
value specifies that the background image size should be as small as possible, ensuring that the size of the image is equal to the size of the container.
Example: Program to scale image in the background using background-size: contain
Here in this program, we have used background-size: contain
to fit the background image within the div container.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<style>
.container {
background: url("https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/tutorials/uploads/pictures/1626423162-101156.png") no-repeat;
background-size: contain;
width: 500px;
height: 200px;
border: 3px solid blue;
margin: 20px;
}
</style>
<body>
<h2> scale image to fit background using CSS</h2>
<div class="container">
</div>
</body>
</html>
Output:
Here is the output of the above program.
Example: Scale image in the background using background-size:cover
In this example, we have used background-size:cover
to fit the image to the background of the div container.
Conclusion
Here we have learned to stretch and scale images to fit the background using CSS. The background-size property is used to do so. The cover and contain values are used to resize the background size of the image.