A simple solution for a CSS responsive background image

One of the problems I've encountered when I started to develop responsive websites was the ability to create a CSS responsive background image. Then I've found a solution which, for now, it is a good one and I would like to share it with you.

The solution it is simple and it implies to use background-size: 100%; for the container which has the background image and also, to make it fully responsive, a new conainer with top padding it is needed. Let's see exactly how will this work on Bootstrap 3.0 CSS framework.

Bootstrap CSS responsive background image example

We will use the below image to make it a responsive background of a <div>.

responsive background

The image will actually have 1170 pixels wide and 426 pixels height. So we will have Bootstrap .container which it is 1170 pixels wide and inside of it will have a <div> with .col-md-12 class which it is 100% wide. BUT, .container has 15px of padding on either side making the inside of the container a total of 1140px due to the box-sizing CSS for all elements being set to border-box by default. Then we will add another class to this last <div>. This class will be .bgimage and will look like this:

.bgimage {  
background-image: url(images/responsive-background.jpg);  
background-size: 100%;  

To make this a CSS responsive background image we will need to add a <div> inside the last one. This <div> will have .bgimage-inside class. This <div> will actually do the trick to make the background responsive by having a specific top padding added to it. This is percentage based and it is calculated using this formula: (image height*100)/image width. So in our case the top padding will be: (426*100)/1170 = 36.41. So .bgimage-inside class will look like this:

.bgimage-inside {  
padding-top: 37.36%; /\* this is actually (426/1140)\*100 \*/  
<div class="container">
 <div class="row">
  <div class="col-md-12 bgimage">
   <div class="bgimage-inside"></div>

Attention! You will notice that I have used .row <div>. Bootstrap adds a negative margin to each row (-15px by default) making each row 1170px wide, but I did not use this width when I calculated the .bgimage-inside top padding. I used 1140px. Why? Because, actually, for the background, the real width of the <div> is 1140px. If you use 1170px then the top padding will be smaller than the image height which is wrong.

And that's it! We have now a perfectly CSS responsive background image.

Comments closed

Please contact me, if you have any questions or suggestions.