Scaling a CSS container within bounds

August 2017

In CSS constraining an element within the bounds of it's parent whilst maintaining it's aspect ratio is harder than you might imagine. This little JS Fiddle from danield770 was just the ticket:

div#constrained-element {
  width:       100vw;
  height:      56.25vw; /* 100/56.25 = 1.778 */
  max-height:  100vh;
  max-width:   177.78vh; /* 16/9 = 1.778 */
  margin:      auto;
  position:    absolute;
  top:         0;
  bottom:      0; 
  left:        0;
  right:       0;

Effectively it uses the CSS3 viewport width/height property to calculate the proper size (in this case 16:9).