Skip to content

Instantly share code, notes, and snippets.

@xavierartot
Created August 13, 2015 14:21
Show Gist options
  • Save xavierartot/ac8ef06e8078266fb154 to your computer and use it in GitHub Desktop.
Save xavierartot/ac8ef06e8078266fb154 to your computer and use it in GitHub Desktop.
Ratio with mixins
https://css-tricks.com/snippets/sass/maintain-aspect-ratio-mixin/
@mixin aspect-ratio($width, $height) {
position: relative;
&:before {
display: block;
content: "";
width: 100%;
padding-top: ($height / $width) * 100%;
}
> .content {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
}
The mixin assumes you'll be nesting an element with the class of content inside your initial block. Like this:
<div class="sixteen-nine">
<div class="content">
insert content here
this will maintain a 16:9 aspect ratio
</div>
</div>
Using the mixin is as easy as:
.sixteen-nine {
@include aspect-ratio(16, 9);
}
Result:
.sixteen-nine {
position: relative;
}
.sixteen-nine:before {
display: block;
content: "";
width: 100%;
padding-top: 56.25%;
}
.sixteen-nine > .content {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment