0

I am trying to set the aspect ratio of a div to portrait (9:16) like this..

.ratio {
  position: relative;
  height: 0;
  width: 100%;
  background: teal;
  padding-bottom: 177.77%;
}
<div class="ratio">
  16:9
</div>

This is working as expected, but I am now wanting to make it so that it has a maximum height of 100% of the viewport.

I am trying to make sure it fits exactly onto the screen whilst keeping the aspect ratio and not introducing scrollbars.

What's my best approach?

Andrzej Ziółek
  • 2,241
  • 1
  • 13
  • 21
fightstarr20
  • 11,682
  • 40
  • 154
  • 278

2 Answers2

2

You will need to use the ratio of 16/9 = 1.778 to calculate the width using calc() css function

body {
  margin: 0;
}

.ratio {
  position: relative;
  height: 100vh;
  background: teal;
  width: calc(1.778 * 100vh);
  margin: auto;
}
<div class="ratio">
  16:9
</div>
Bhuwan
  • 16,525
  • 5
  • 34
  • 57
-1

I would recommend then using the vh unit for the height then.

height: 100vh;
Keith
  • 144
  • 1
  • 6