The background-size CSS property is used to set the size of the element's background image.
Syntax
background-size: cover|contain|auto|value;
Value | Description |
cover | Scales the image without stretching it to cover the entire container. The image may be cropped vertically or horizontally so that no empty space is left. |
contain | Scales the background image without cropping it. |
auto | The image is scaled without cropping or modifying it's properties. This is the default value. |
inherit | The property is inherited from the parent element. |
value | You can set the width and height of the background image. If only one value is specified, the second value will be auto. Eg: background-size: 10px 20px; |
Example - background-size:auto
<!DOCTYPE html>
<html>
<head>
<title>CSS background size</title>
<style>
body{
background-image: url('pics.jpeg');
background-size: auto;
background-repeat: no-repeat;
}
</style>
</head>
<body>
</body>
</html>
Output
Example - background-size:cover
<!DOCTYPE html>
<html>
<head>
<title>CSS background size</title>
<style>
.ms-cover{
background-image: url('pics.jpeg');
background-size: cover;
background-repeat: no-repeat;
min-height:200px;
}
</style>
</head>
<body>
<div class="ms-cover"></div>
</body>
</html>
Output
Example - background-size:contain
<!DOCTYPE html>
<html>
<head>
<title>CSS background size</title>
<style>
body{
background-image: url('pic.jpeg');
background-size: contain;
background-repeat: no-repeat;
}
</style>
</head>
<body>
</body>
</html>
Output
Example - background-size:value
<!DOCTYPE html>
<html>
<head>
<title>CSS background size</title>
<style>
div{
min-height:200px;
}
.ms-value1{
background-image: url('pic.jpeg');
background-size: 100px 150px;
background-repeat: no-repeat;
}
.ms-value2{
background-image: url('pic.jpeg');
background-size: 30% 60%;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<div class="ms-value1"></div>
<div class="ms-value2"></div>
</body>
</html>
Output
Learn about the shorthand CSS background property.
Subscribe
Join the newsletter to get the latest updates.