The background-size
property in CSS is used to specify the size of the background image. It allows you to control how the background image is stretched or scaled to fit its container.
background-size
The default value. The background image is displayed at its original size.
.example1 {
background-image: url('background.png');
background-size: auto;
}
Scales the background image to be as large as possible so that the background area is completely covered by the image. Some parts of the image may be clipped to fit.
.example2 {
background-image: url('background.png');
background-size: cover;
}
Scales the background image to be as large as possible while ensuring both its width and height fit within the container. The entire image is visible, but it may not cover the entire background area.
.example3 {
background-image: url('background.png');
background-size: contain;
}
You can specify the width and height using length values (e.g., pixels, ems).
.example4 {
background-image: url('background.png');
background-size: 100px 200px;
}
You can specify the width and height as percentages of the container's dimensions.
.example5 {
background-image: url('background.png');
background-size: 50% 50%;
}
If you specify one value, the other dimension is set to auto
.
.example6 {
background-image: url('background.png');
background-size: 100px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Background Size Example</title>
<style>
body {
font-family: Arial, sans-serif;
}
h2 {
margin-top: 20px;
}
.size-example {
width: 300px;
height: 200px;
background-image: url('background.png');
background-repeat: no-repeat;
border: 1px solid #000;
}
</style>
</head>
<body>
<h2>Auto</h2>
<div class="size-example" style="background-size: auto;"></div>
<h2>Cover</h2>
<div class="size-example" style="background-size: cover;"></div>
<h2>Contain</h2>
<div class="size-example" style="background-size: contain;"></div>
<h2>100px 200px</h2>
<div class="size-example" style="background-size: 100px 200px;"></div>
<h2>50% 50%</h2>
<div class="size-example" style="background-size: 50% 50%;"></div>
<h2>100px</h2>
<div class="size-example" style="background-size: 100px;"></div>
</body>
</html>