Maintain aspect ratio of a responsive element

10 Jun 2016

There are many situations where you want your responsive elements to maintain their aspect ratio.

For e.g., Making a responsive image button using an anchor tag.

The image will be set as a background image and we would expect the button to resize based on the aspect ratio of the background image. The immediate thought would be to use Height in percentage(%). But height in % will not work out for normally positioned elements. You need to have position:absolute for the height to work with percentage.

So how can we achieve a responsive behavior where aspect ratio can be maintained ?

CSS has a very neat solution for this requirement. Following CSS will allow the elements to change its height based on the width, there by maintaining the aspect ratio.

a.img-btn
{
  background:url("../mybutton.jpg");
  width:50%;
  padding-top:50%; //Same width and padding will create a square
  height:0;
}

The Key in above technique,

"Padding is always calculated based on the width of the element"

So we will make the non-useful height as 0 px, and we will control the height of the element using padding top or bottom as shown in above CSS example. This would allow us to control the aspect ratio accurately as we expect. Above CSS can be applied to our anchor button as shown below:

<a href="#" class="img-btn">This is a Responsive image button</a>

Happy Coding !