Is there a way to achieve this only in CSS, without JavaScript?
I need a div with the following requirements:
- it ALWAYS maintains a given aspect ratio (for example, 4: 3).
- its width never exceeds a given fixed maximum in px, for example. 800px
- its height never exceeds a given fixed maximum, for example. 600px
- its dimensions never exceed the dimensions of the viewport.
- it is as large as it can get the above restrictions
- it is centered both vertically and horizontally
In other words, it should fill either the width or height of the viewport, depending on which is more constraining, while maintaining this aspect ratio; if it does not exceed a fixed maximum width and / or height, in which case it will be limited to this.
I don't care how many wrappers inside inside I need.
I know this answer provides a solution to a fixed aspect ratio limited by the width of the parent, and it is easy to add a fixed max-width constraint with an additional wrapper; but I see no way to adapt this to add height restrictions.
source
share