CSS HTML

How to make a background image fill the entire screen

December 13, 2021

How to make a background image fill the entire screen

In this article we will see how to make a background image fill the entire screen, without losing its resolution, in a very simple way with pure CSS.

make a background image fill the entire screen cover

What’s up programmer, okay? Let’s learn something new!

Watch this content on YouTube:

To solve this problem, we first need to have a container that fills the entire screen.

We can use the vh media unit, view height, which with a value of 100 can do this

And in the same way an average of vw, view width, with a value of 100 for the width

Next, and not least, you need to have an image large enough to support the various resolutions available.

It may seem silly this detail, but many people forget about it and this is the problem with the distorted image

And finally let’s insert this image with background via CSS, and add a property called background-size with the value of cover

That will make the image fill all the available container, solving our problem, let’s go to a practical example:

<!DOCTYPE html>
<html>
 <head>
  <title>How to make a background image fill the entire screen</title>
  <meta charset="utf-8">
 </head>
 <body>
  <div id="image-container"></div>
 </body>
</html>

This will be our HTML, very simple, it only contains the image div that will fill the entire screen

And now the first step of CSS:

body {
 margin: 0;
}

#image-container {
 position: relative;
 height: 100vh;
 width: 100vw;
 background-color: red;
}

With that, we eliminate an unnecessary margin from the body, and create the container that fills the entire screen

Do you want to specialize in Web Development? Check out our course catalogue.

Now your entire screen should be red, let’s make the change to the image:

body {
 margin: 0;
}

#image-container {
 position: relative;
 height: 100vh;
 width: 100vw;
 /* adicionando imagem de fundo */
 background: url('bg-img.jpg');
 background-size: cover;
}

That’s it! We changed the background-color to the properties we mentioned in the introduction and now the problem is solved 

Tip: You can better position your image with the background-position rule

Conclusion

In this article, we learned how to make a background image fill the entire screen without losing quality or distorting

First we create a container that fills the entire screen with vw and vh

Then we add the background image via CSS with the background property

And finally we add background-cover for the image to fill the entire screen or the entire container

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x