Skip to content

Instantly share code, notes, and snippets.

@knolaust
Last active January 30, 2024 14:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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;
}
}
}
@kdbruin
Copy link

kdbruin commented Mar 14, 2022

Nice solution but the fallback doesn't respect the given width and height if I read it correctly. Shouldn't this be something like:

padding-top: calc(100% * #{$height} / #{$width});

@knolaust
Copy link
Author

Yep. I didn't even realize I left test ratio for 1/1 in there. Made some fixes and also removed the divs before the :before and :after. Thanks for pointing out.

@kromakollision
Copy link

The fallback won't work if the browser doesn't support @supports, which is probably almost equal to all browsers that don't support aspect-ratio

@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