Keeping the aspect ratio of a <div>
or similar element while being responsive to the parent's size seems to be a common problem. The solution that is widely regarded across the net as being the most elegant one is this:
Maintain the aspect ratio of a div with CSS
Using a wrapper element and defining the aspect ratio via the width
and padding-bottom
element, both of which are relative to the parent size.
div.wrapper {
width: 30%;
padding-bottom: 30%;
}
Now, my current problem is, that I need to introduce to introduce a max-height
to these wrapper elements in order to make sure, that at least two rows of them fit the screen, independent of the viewport size. Adding max-height
to the example above limits the element's height, but leaves the width unchanged.
However, an aspect ratio of 1:1 still needs to be maintained, even if the height is restricted via max-height
. Also, I would like to have the group of wrapper elements (three or four columns, two rows) in the center of the viewport/parent.
Is there any pure html/css way to achieve this (without javascript)? I would not mind using <img>
elements with a source of the desired ratio as I have to apply (background) images to these elements anyway but a universal, elegant solution as for the problem above would be appreciated.