Setting the size of a background image using CSS allows you to control how the image fits within an element. By using the background-size property, you can specify the width and height, ensuring the image scales appropriately for responsive design.
Syntax:
background-size: width height;Note:
- If the first value is omitted then the image takes its original width.
- If the second value is omitted then the image takes its original height.
Example 1: In this example, we use CSS to set a background image in a <div> with specified dimensions. The background-size property ensures the image fits the container of 400px width and 200px height.
<!DOCTYPE html>
<html>
<head>
<title>
Set the size of background image
</title>
<style>
#myDiv {
height: 200px;
width: 400px;
background:
url(
"https://media.geeksforgeeks.org/wp-content/uploads/gfgbg.png");
background-size: 400px 200px;
}
</style>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
Output:

Example 2: In this example we sets a background image in a <div> with dimensions 400px by 200px. The background-size property adjusts the image size to 70% of the container's width while preventing repetition.
<!DOCTYPE html>
<html>
<head>
<title>
Set the size of background image
</title>
<style>
#myDiv {
height: 200px;
width: 400px;
background:
url(
"https://media.geeksforgeeks.org/wp-content/uploads/gfgbg.png");
/* Set the background-size in percentage */
background-size: 70%;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
Output:
