Skip to content

Instantly share code, notes, and snippets.

@knolaust
Last active January 30, 2024 14:55
Show Gist options
  • Save knolaust/2e5cc0b14c7e7c68ae9b1e4d7074cdaa to your computer and use it in GitHub Desktop.
Save knolaust/2e5cc0b14c7e7c68ae9b1e4d7074cdaa to your computer and use it in GitHub Desktop.
Sass Mixin For CSS Aspect-Ratio With Fallback
/**
* 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;
}
}
}
@knolaust
Copy link
Author

Good point. I first started using this in 2021 when @supports had decent support and aspect-ratio was new and not well-supported. There's now a 3% difference between aspect-ratio and @supports... At this point the fallback can probably be removed entirely.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment