A Responsive CSS Background Image Technique

While working my day job, I came across the need to make a background image responsive, keeping the same aspect ratio at different widths. The limitation was that we couldn’t change any HTML or back end code so changing it to a simple img was out of the question. I then found the following technique somewhere on Stack Overflow but unfortunately I forgot to bookmark the link so I thought I would document it here. If I find the link (or if anyone knows of it or finds it and sends it in), I will add it to this post to give proper credit.

Demo

The Technique

To give a background image to an element when you want the whole image to display, you have to define the height and width to be the same size as the image itself (you can’t apply this technique to image sprites unfortunately) but that doesn’t work well with responsive layouts. The width is fine but specifying a height is problematic if you want the image to scale, keeping the same aspect ratio and without leaving space below or chopping off the image.

The way around this is so set the height to 0 and work out the height depending on the aspect ratio of the image itself and use padding-bottom to reveal the image instead. To do this you have to divide the width by the height and multiply by 100. This is the percentage of width to height which is then applied to the bottom padding as a percentage to reveal the image and will now keep the aspect ratio of the image and the element it is applied to consistent at all widths. You’ll also need to use background-size: 100% to keep the image the same size as the element.

HTML

<a class="background" href="#">Background Image Applied Here</a>

CSS

.background {
	display: block;
	height: 0;
	padding-bottom: 62.571428571429%;
	background: url(image.jpg) no-repeat;
	background-size: 100%;
	text-indent: -9999px;
}

This isn’t a fix-all technique but it does work in this specific example and I know I’ll be using it again and again in the future.

by @tkenny

You should follow me on Twitter here

Newsletter

Subscribe to the Inspect Element email for updates on articles, tutorials and WordPress themes: