How to maintain html container aspect ratio using CSS only

The title is a bit misleading as simply maintaining the aspect ratio and the html element is trivial using width and padding-bottom or padding-top percentages. However, my scenario is slightly different. Perhaps the solution is just as trivial, but my brain is frying.

So, in my case, I have a content div inside a container div. The container div is expected to be of any size and size. The requirement is that the inner div must maintain its own aspect ratio, but must also match either the height or width of the container div, whichever is closer to the aspect ratio of the content of the div.

So, for example, my content div has an aspect ratio of 16: 9. My container div is currently 500px wide and 1000px high. In this case, my content div will be 500px in size and 281px in height, with a space above and below the div content. The container div can now be resized to 1000px wide and 500px high, in which case the content div will resize to 889px wide and 500px high with space to the left and right of the div content.

Probably a less complicated way to explain this scenario, but then again, my brain is frying today. Any help would be appreciated.

EDIT: I'm looking for a CSS only solution. I know this is possible with JS / JQuery.

+3


source to share


1 answer


What you would like to do is use something like this object-fit: cover

to have the best effects in your case. Unfortunately a CSS only solution in this case will not give the desired results, as above, JavaScript / jQuery is required.



0


source







All Articles