Sass Mixin For CSS Aspect-Ratio With Fallback

01/30/2024
Back to Blogs
/**
  * Include this Sass mixin for aspect-ratio. Includes fallback
  * for browsers that do not support aspect-ratio. This fallback is really not necessary at this point unless
  * a specific browser you need to support.
  * 
  * Usage:
  * @include aspect-ratio(16,9);
  * creates a 16x9 container using aspect-ratio for supported browsers with fallback for browsers that do not. 
  * 
  * Codepen Example: https://codepen.io/knolaust/pen/KKZwXjv
  * Gist Keywords: sass, scss, mixin, aspect ratio
  *
  */
@mixin aspect-ratio($width, $height) {
  aspect-ratio: $width / $height;
  // Fallback (current, using padding hack)
  @supports not (aspect-ratio: 1 / 1) {
     &::before {
      float: left;
      padding-top: calc(100% * #{$height} / #{$width});
      content: "";
    }
    &::after {
      display: block;
      content: "";
      clear: both;
    }
  }
}