How to make a background-image responsive?

August 11, 2020
Thomas Duffy

Written by Thomas Duffy

Making a div responsive

Today we’re going to talk about making a background-image responsive.

First, let’s understand why this is even an issue. When you need to make an image responsive, there are two main ways to do it. You can use an image tag, or you can use a div with a background image.

Making an image tag responsive is quite trivial. You can give it a width of 100% and a height of auto and call it a day.

<img src="responsive.jpg" width="100% />

When making a div with a background-image responsive, you don’t have the luxury of using the height of the image to scale the divs height along with the width. Below is what you get if you don’t manually set the height when using a background image.

.background-image {
  background-image: url("responsive.jpg");
  background-position: center center;
  background-size: contain;
  width: 100%;
}

No height

Setting a min-height also won’t work for the same reason as above.

.background-image {
  background-image: url("responsive.jpg");
  background-position: center center;
  background-size: contain;
  width: 100%;
  min-height: 300px;
}

Padding-bottom to the rescue

Alright, enough of what doesn’t work. The hack to get around this scenario is by merely giving the div in question a property of padding-bottom with the ratio of the image you’re setting as the background image.

To get the ratio, you divide the images height/width.

(height / width) = padding-bottom
.background-image {
  background-image: url("responsie.jpg");
  background-position: center center;
  background-size: contain;
  width: 100%;
  height: auto;
  padding-bottom: 69%;
}

Recap

So the only gotcha is that you need to know the ratio of the image to make sure it doesn’t get cut off while scaling. I’m sure you can think of other ways to use this technique in the world of responsive web. I hope you enjoyed this post about making a background-image responsive.


Thomas Duffy

Written by Thomas Duffy