Enter your email below to get insights on starting, running and growing a creative company

Scaling a CSS container within bounds

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).

Posted August 2017
© 2014-2018 James Chambers
Learn from my mistakes

Sign up to my mailing list to get insights about starting, running and growing a creative company.