Maintain Aspect Ratio for HTML Element Using Only CSS in a Responsive Design

There is an easy way to make a div or other element square or any other shape while still being responsive, using ONLY CSS. I actually stumbled upon this solution myself, and then saw a formal write-up of it by @marcolago here. The solution is actually extremely simple, and you will kick yourself for not figuring it out. This little trick can make developing a responsive website design significantly easier.

The key lies in padding. Padding, whether being used to define top, bottom, left, or right padding, is dependent upon the WIDTH of the containing element when defined in percents. For example, if you say “padding-top: 10%;” what you are actually saying is that the padding on the top should be 10% of the WIDTH of the containing element. So then, if you wish to make an element a responsive square, you simply write this:

The height needs to be set at zero, so that the entirety of the element’s height is produced from the padding. But with these simple lines of code, you can easily have boxes or other elements that resize gracefully in the browser along with all of your other responsive elements. Happy coding!

Tired of dealing with your slow WordPress website? Email me at brian@pagecrafter.com and mention the code #FreeHosting10 for two free months of lightning-fast WordPress hosting. We will even migrate you for free!

If you need any help implementing this, you can ask me on twitter at @brianjonline or email me at brian@pagecrafter.com.

About Brian Johnson

Brian Johnson is a website developer and designer living in Minneapolis, Minnesota with a passion for code and WordPress. He spends his days building WordPress websites for small businesses, developing new code with the online community, and living life.