Home »
CSS
How to make background image fit on screen using CSS?
Since, in designing a website sometimes we need a banner image that fits on screen without any space around the image. And sometimes we need a section that filled with background image without any space around that section. So, in this we will learn how we can make background image fit on screen?
Submitted by Prerna Saxena, on October 13, 2017
We specify background properties like URL of background image, size of background-image, whether it should repeat or not, position of background images we also specify background without images. We will specify it as:
background-color: red;
background-size: 1000px;
background-repeat: repeat-x;
background-image: url('images/image.png');
background-position:center;
Since providing CSS on body will cover whole body of html document that is it will cover whole window screen. We can provide background-color on body as follows:
body{
background-color:red;
background-size:cover;
background-repeat:no-repeat;
}
It will fill screen with red color due to background-color is applied on body element. Similarly if we apply background-image to body it will cover whole screen with some margin which will be removed by background-size to cover.
Setting the background-repeat property to no repeat will not repeat the image horizontally or vertically. We can repeat an image Horizontally by setting the background-repeat:repeat-x or repeat vertically by setting the background-repeat:repeat-y
Setting the background-size to cover will cover the entire width of container. It will stretch the image within the width of container.
We can set image to fit within the container using image width:100% and height:100%. Use the following code:
For example:
If we want to fit the image within the div we will use following CSS and html code:
HTML code
<body>
<div class="bgimg">
<img src="images/landscape.jpg" class="imgstyle">
</div>
</body>
CSS code
.bgimg{
width:1000px;
height:400px;
margin:auto;
}
.imgstyle{
width:100%;
height:100%;
}
It will fit perfectly within the div section without any space around the div.
HTML with CSS
<html>
<head>
<title>Fit image on screen</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>
body{
background-image:url('images/landscape.jpg');
background-size:cover;
background-repeat:no-repeat;
}
</style>
</head>
<body>
</body>
</html>
CSS Tutorial & Examples »