Last active
January 30, 2024 14:55
-
-
Save knolaust/2e5cc0b14c7e7c68ae9b1e4d7074cdaa to your computer and use it in GitHub Desktop.
Sass Mixin For CSS Aspect-Ratio With Fallback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
} | |
} |
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.
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
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
Nice solution but the fallback doesn't respect the given width and height if I read it correctly. Shouldn't this be something like: