Before you go, check out these stories!

0
Hackernoon logoAdd Responsive Background Images To Your Web Pages [A How To Guide] by@daniel-wesego

Add Responsive Background Images To Your Web Pages [A How To Guide]

Author profile picture

@daniel-wesegoDaniel Wesego

Loved by God

Background images are a wonderful way of styling your pages. Adding background images will help you catch your readers’ attention. But this all won’t be enough if you are doing it wrong.

You should make your background images responsive. Being responsive will make them automatically resize as the screen size of the viewer. In this article, we will learn how to make responsive background images using HTML and CSS. 

It is better to use high-quality images so that the image quality won’t be low on big screens.

Let’s begin by creating the files. Create two empty files and save them with html and css extension. You can name them anything. Add your css file to the html with the link tag in your header.
Also, move your image file here. For better arrangements, you can put the css and the image file in separate directories but we will put them all in one folder for this demo. 

First, let’s see how to make a full-page responsive background image. In your html file, put any text just to see in front of your background image. I will put an H1 header:

<body>
 <div>
   <h1 class="title">Responsive Background Image</h1>
 </div>
</body>
In your css file, put the following:
body {
 background-image: url(./path_to_image);
 background-size: cover;
 background-attachment: fixed;
 background-repeat: no-repeat;
 background-position: center; 
}

Well, that’s it. Open your html in your browser and you will see that your background image has filled your page. The ‘background-size: cover’ is the main property that made this possible. This property tells the browser to scale the background image proportionally. The ‘background-attachment: fixed’ property makes it fixed on your screen giving you a beautiful scene. 

Ok, so what if you want to put the background image on a DIV and not the whole body. You need a div with a fixed height and a width of 100%. The html part is shown here.

<body>
 <div class="background-image">
   <h1 class="title">Responsive Background Image</h1>
 </div>
</body>

The css will look like this.

.background-image {
 height: 1200px;
 width: 100%;
 text-align: center;
 background-image: url(./path_to_img);
 background-size: cover;
 background-attachment: fixed;
 background-repeat: no-repeat;
 background-position: center; 
}

Here the background image will be responsive with respect to the div. That’s it about responsive background images. I hope you liked it.

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!