Mission
While working on a dashboard I ran into the puzzling question of how I could create a responsive layout containing divs that would always be square, no matter what their size.
Solution
I did some research and found a nice, clean solution using an :after element, and padding-top and/or padding-bottom.
Something like this:
See the Pen Aspect Ratio Div by TMichel Productions (@TMichelProductions) on CodePen.0
Original CodePen Pen can be found here
Additional Steps
If you change the width attribute on the .aspect style, you will see that the height automatically changes to be a 1:1 ratio. This is because the empty :after element is taking 100% of its parents width and applying it to its own height. This applies the aspect ratio.
You will also notice that the child is set to position: absolute. This is to keep from adjusting the size of the div to something other than it’s aspect ratio.
Changing the aspect ratio is as simple as changing the padding-top on the .aspect:after style. Some ratios to try:
2:1 = padding-top: 50%;
3:1 = padding-top: 33%;
1:2 = padding-top: 200%;
1:3 = padding-top: 300%;
For custom aspect ratios simply divide the height by the width and multiply the result by 100. For example if you wanted an aspect ratio of 4:1, you would divide 1 by 4, giving you 0.25. Multiplying that by 100 you end up with 25% for your padding-top property.
And that’s it!
Hope this helps in your adventure to web coding!