Maintain Aspect Ratio Mixin

0
0

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;
}
  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.