How to style a div to be a responsive square?

danijar picture danijar · Sep 28, 2013 · Viewed 272.7k times · Source

I want my div to adapt its height to always equal its width. The width is percental. When the parent's width decreases, the box should decrease by keeping its aspect ratio.

How to do this is CSS?

Answer

rahulbehl picture rahulbehl · Sep 28, 2013

Works on almost all browsers.

You can try giving padding-bottom as a percentage.

<div style="height:0;width:20%;padding-bottom:20%;background-color:red">
<div>
Content goes here
</div>
</div>

The outer div is making a square and inner div contains the content. This solution worked for me many times.

Here's a jsfiddle