JSFiddle - React, Tailwind, and code Playground

by joshmoto

HTML

<div class="fixed-ratio">

</div>

CSS

.fixed-ratio {
  max-width: 600px;
  width: 100%;
  background: red;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}

.fixed-ratio:before {
  content: '';
  width: 100%;
  padding-top: 66.6664%;
  display: block;
}

JavaScript

/*

Ahh the oldest rick trick in the book...

So you say you want a div centred in your window, and the div must stay at a fixed ratio at all times, but of course be responsive to window resizing.

Lets say your div ratio is 4 x 6...

And lets say you want the div to only be a max-width of 600px.

To get the ratio height of our div in a percentage, the math is 100 / w * h, which for our 4 x 6 example, equates to 66.6664%

Simply do this, css only...

.fixed-ratio {
  max-width: 600px;
  width: 100%;
  background: red;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}

.fixed-ratio:before {
  content: '';
  width: 100%;
  padding-top: 66.6664%;
  display: block;
}
See working demo here... https://jsfiddle.net/joshmoto/jgp48r1m/

*/