Responsive Aspect-Ratio SCSS Mixin
Mixin to lock the aspect ratio of an element – or make it fit to content if it exceeds the boundaries of the aspect ratio.
Note! the ratio is produced using the :before and :after pseudo-elements – why it won't work on empty tags like <img />, <input /> etc.
1:1
16:9
9:16
4:3
4:3
Fit to content
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Resize window
Use examples
// Syntax:
// @include aspect-ratio($ratio or $width, $height);
.class { @include aspect-ratio(); } // No arguments defaults to a 1:1 ratio
.class { @include aspect-ratio(16, 9); } // Width and height
.class { @include aspect-ratio(1.777778); } // Ratio (calculated width/height)
.class { @include aspect-ratio(4px, 3px); } // Comparable units
.class { @include aspect-ratio($ratio: 1.2); } // Keywords
The mixin
@mixin aspect-ratio($arglist... /*$ratio or $width, $height*/){
$map : keywords($arglist);
$height: map-get($map, height) or nth-or-null($arglist, 2);
$width: map-get($map, width) or nth-or-null($arglist, 1);
$ratio: map-get($map, ratio) or if($width and $height, $width/$height, nth-or-null($arglist, 1)) or 1;
$padding: 1/$ratio * 100%;
&:before { content: ''; float:left; padding-bottom: $padding; margin-right:-100%;}
&:after { content: ''; display:table; clear: both; }
}
// Helper function
// Return null rather than throwing an error if index is outside list range.
@function nth-or-null($list, $index) {
@return if(length($list) >= $index, nth($list, $index), null);
}