CSS HTML

How to make a background image responsive with CSS

December 3, 2021

How to make a background image responsive with CSS

In this article we are going to learn how to make background image responsive only with CSS in a quick and easy way.

background image responsive cover

Hey you programmer, okay? Let’s learn something new!

Adding images as the background of a <div> is a very common action on the web.

Because sometimes we need to add some text in front of the image, so from a maintenance point of view it’s much easier to do that than an <img tag>

So, there is a need to make the image responsive, as the image may be too large or even need to be resized

So to solve our problem, let’s go to an example structure:

<!DOCTYPE html>
<html>
 <head>
  <title>Como deixar uma imagem de background responsiva</title>
 </head>
 <body>
  <div id="container"></div>
 </body>
</html>

Here a very simple HTML structure, just with the div we need to add the background image

Now let’s go to CSS, add a background image to this div

Check out the code:

#container {
 width: 400px;
 height: 400px;
 background-image: url('./bg-img.jpg');
}

This code will make the image appear in the browser, like this:

However, it is decentralized and huge for the space destined

Then comes the need to make it responsive, and for that we need to add a property called background-size with the value cover

#container {
 width: 400px;
 height: 400px;
 background-image: url('./bg-img.jpg');
 background-size: cover;
}

Check out the return now:

We then have our problem solved, the image is perfectly adapted to our area

The cover value specifies that the background image must be sized according to the container, ensuring that both dimensions (height and width) are greater than or equal to the container

Conclusion

In this article we learned how to make an image added by background-image becomes responsive

We just need to add the background-size property with the value of cover

Want to learn more about CSS? Click here!

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