Maintain Element Aspect Ratio Using CSS Only

Share

Tweet

by Cameron Alcorn August 26, 2014   Freebies

Aspect ratio doesn’t seem like a problem, until you try to make a web page responsive. If you’ve ever pulled your hair out trying to get an element or image to maintain its aspect ratio, give your scalp a break. There is a way, that was brought to my attention by web dev, Brian Johnson.


That Aspect Ratio

Surprisingly, it’s all in the padding, or padding-bottom, to be more specific.

Take the example below:

The CSS


width: 100%;
height:0;
padding-bottom:50%;

No matter how you resize the window, the <div> will keep the 2 x 1 aspect ratio.


How It Works

If you base an element’s height off of the height property, the element’s height will actually be based off of its parent element’s height, thus, losing its intended aspect ratio. However, an element’s padding is based off of it’s width property, meaning it stays proportional. So, by setting the height to 0 and by, instead, relying on padding-bottom, you can maintain aspect ratio.


Did you find this tutorial helpful? Follow me on Twitter for more.

  Comments

Written by
Business professional by day, web developer by night, when I’m not creating solutions for my clients, I’m writing or creating meaningful content for the Web.

Posted In
Freebies

Resources & Code Snippets