Skip to content

Instantly share code, notes, and snippets.

@raekul
Created November 15, 2016 08:25
Show Gist options
  • Save raekul/977ba583e4f4f4d2d7a246f1f887f270 to your computer and use it in GitHub Desktop.
Save raekul/977ba583e4f4f4d2d7a246f1f887f270 to your computer and use it in GitHub Desktop.
// The mixin
@mixin set-ratio($width, $height, $selectors...) {
// needed on the parent so the absolute childs reference it
position: relative;
// create our ratio with the psuedo before
&:before {
display: block;
content: "";
width: 100%;
padding: 0 0 percentage($height/$width) 0;
height: 0;
}
// check length of selectors and provide default if non exist
@if length($selectors) == 0 {
$selectors: img
}
// loop through selectors and create direct descendent selector
@each $selector in $selectors {
> #{$selector} {
z-index: 100;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
}
}
}
// You might have a structure like so
// <div class="parent">
// <div class="container">
// <div class="child"></div>
// </div>
// </div>
// Using Mixin
.parent {
// first 2 arguments is the ratio you want to use
// Last argument or (arguments) are the elements you want to apply the required css above to.
@include set-ratio(16, 9, div);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment