Maintain Aspect Ratio Mixin

Avatar of Chris Coyier
Chris Coyier on (Updated on )

This article from July 2013 describes a method of using psuedo elements to maintain an elements aspect ratio, even as it scales.

Here’s a Sass mixin that simplifies the math a bit.

@mixin aspect-ratio($width, $height) {
  position: relative;
  &:before {
    display: block;
    content: "";
    width: 100%;
    padding-top: ($height / $width) * 100%;
  }
  > .content {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }
}

The mixin assumes you’ll be nesting an element with the class of content inside your initial block. Like this:

<div class="sixteen-nine">
  <div class="content">
    insert content here
    this will maintain a 16:9 aspect ratio
  </div>
</div>

Using the mixin is as easy as:

.sixteen-nine {
  @include aspect-ratio(16, 9);
}

Result:

.sixteen-nine {
  position: relative;
}
.sixteen-nine:before {
  display: block;
  content: "";
  width: 100%;
  padding-top: 56.25%;
}
.sixteen-nine > .content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

Demo

Here’s a demo showing the above code in action. The animation is added to show the element maintaining the assigned aspect ratio as it resizes.

See the Pen Maintain Aspect Ratio Demo by Sean Dempsey (@seanseansean) on CodePen.

Thanks to Sean Dempsey (@thatseandempsey) for this one!