Keeping aspect ratio in responsive CSS

Having problem with retaining the aspect ratio when doing responsive design? Setting width in percentage is easy, but doing the same for height will be ignored. The solution is to instead use padding in order to set the correct aspect ratio. In order for this to work the height must be set to 0.

The example below shows an element that will keep a 4:3 aspect ratio when scaled. The percentage set as padding-bottom will be the ratio, so for 4:3 we'll use 75%. If you instead want a complete square you should use 100%.

<style>

.my-box {
background:#cccccc;
width:100%;
height:0;
padding-bottom:75% /* relative to the element´s width */
}

</style>

<div class="my-box">
This box should be 4:3
</div>

Original solution found at: Pixel Acres

Related posts:

Comments

comments powered by Disqus