The example below will show you how to set a full background image as well as half background.
Let’s download one high definition image first. Use the following link from Pixbay to download image. Although, you can choose your own image. This is just for the example purpose only.
Click to download image
Awesome. Now I assume you have a basic knowledge of how HTML works. So, I’ll skip the HTML talks and discuss about the code below.
Your other codes goes here…
What we have done in above code is, creating a div element in simple .html file and assigning it a class “fullBackground”. You can go ahead and add more code if you would like but to learn just about the background image, that code is enough.
Now try to add style to the same .html file or create a new CSS file and include it into the HTML file. [I assume you know how to do that.]
Add the style as in the code below.
body, html {
height: 100%;
margin: 0;
}
.fullBackground {
background-image: url("images/CSS/how to set a full background image using css.jpg");
/* you can have any file name and don't forget to add the extension .jpg */
height: 100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
Let’s discuss the code above.
The background-image property sets any image as the background of any element, in our case, we have a div element. By default, it repeats the image and tries to cover the whole element area.
But, the problem is that by default, the background-image tag or property repeats the image horizontally and vertically both.
To stop browser from doing that we use, background-repeat: repeat-x; or background-repeat: repeat-y;.
x- means repeats horizontally and y menas repeats vertically.
Now, you must have understood that why we’ve used background-repeat: no-repeat;. Yes, exactly. Just to show image once we tell it to stop repeating aka stopping its default behavior.
The background-position property just specifies the position of the image.
And, lastly we use background-size property to specify the size of the background. Checkout the image and it’s default value is auto. You can specify the size in ‘pixels’, ‘percentage’, or using words like ‘cover’-to cover the entire container, ‘initial’-sets the default value etc. etc.
So as you can see now that we’ve set the image as full background.
background background-image