Is there a way to achieve this in CSS-only, without JavaScript?
I want a div with the following requirements:
- it ALWAYS maintains a given aspect ratio (e.g. 4:3)
- its width never exceeds a given fixed maximum in px, e.g. 800px
- its height never exceeds a given fixed maximum, e.g. 600px
- its dimensions never exceed those of the viewport
- it's as big as it can get given the abovementioned constraints
- it's centered both vertically and horizontally
In other words, it should fill either the viewport width or height, whichever is more constraining, while maintaining the given aspect ratio; unless this exceeds the fixed maximum width and/or height, in which case it would be constrained by that.
I don't care how many wrappers one inside another are needed.
I know this answer provides the solution to the fixed aspect ratio constrained by the parent's width, and it's easy to add a fixed-max-width constrain with an additional wrapper; but I can't seem to see a way to adapt that to add the height constraints.