0

How can I create a div that

  • has aspect-ratio 9/16
  • always fully fits in the viewport without scrolling
  • and is horizontally and vertically centered?

On a wide viewport it should look like this:

enter image description here

And on a narrow viewport like this:

enter image description here

Below is my approach that works as long as the viewport is wide, but fails when the viewport gets too narrow.

div {
   border:  1px solid gray;
}
<div style="height: 100%;width: 100%;">
    <div style="display: flex;justify-content: center; align-items: center;height: 100%;width:  100%;flex-direction: column;">
        <div style="aspect-ratio: 9/16; max-width: 100%; height: 100%;">
            <div style="width: 100%; height: 100%">
                i should always have 9/16 aspect ratio and always be visible on the viewport without scrolling. but when viewport gets too narrow, it does not work :(
            </div>
        </div>
    </div>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Patric
  • 1,489
  • 13
  • 28
  • whoever marked this as duplicate, did you read the whole question? I've seen the other one already, but it's not the same! it DOES overflow with a scrollbar instead of shrinking to the height, and i dont want that... also centering at the same time. maintaining the aspect ratio itself is easy... – Patric Apr 11 '22 at 11:18
  • 2
    check this: https://stackoverflow.com/a/65864592/8620333 you can find your answer there (I am updating the duplicate) – Temani Afif Apr 11 '22 at 15:23
  • In fact, it is almost the same with linked question but you have to adapt it more. [Here is my code](https://jsfiddle.net/o5bwsxvc/1/) for you. – vee Apr 11 '22 at 16:16
  • thank you very much - seems to work here :) in my use case i have an additional inner absolute div that makes things a bit more complicated... trying to figure that out currently... what's the reason for the nested min() function with the 2000px? – Patric Apr 11 '22 at 16:26
  • @Patric It's for calculate and detect the minimum size of width based on these data. Otherwise you have to use media queries to set height to prevent it overflow in narrow screen. – vee Apr 11 '22 at 16:29
  • @vee yes i know, but why the value 2000px? why not just `width: min(100%, 90vh*(var(--ratio)));`? – Patric Apr 11 '22 at 16:37
  • @Patric I use big screen but you can change to whatever you want. – vee Apr 11 '22 at 16:51

0 Answers0