Skip to content

Instantly share code, notes, and snippets.

@saeedseyfi
Last active June 8, 2016 11:30
Show Gist options
  • Save saeedseyfi/7bfa4d9e15d64b5179db48d1e7133c97 to your computer and use it in GitHub Desktop.
Save saeedseyfi/7bfa4d9e15d64b5179db48d1e7133c97 to your computer and use it in GitHub Desktop.
A sass mixin + its output with 1x1 and 16x9 sample ratios. This will keep image aspect ratio with pure css, independent from width & height.
/* ratio.scss output: */
.ratio-1-1 {
display: block;
position: relative;
height: 0;
overflow: hidden;
padding-bottom: 100%;
}
.ratio-1-1 img {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
.ratio-16-9 {
display: block;
position: relative;
height: 0;
overflow: hidden;
padding-bottom: 56.25%;
}
.ratio-16-9 img {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
<!-- how to use the css class -->
<div class="ratio-1-1">
<img src="pic_mountain.jpg" alt="Mountain View">
</div>
<div class="ratio-16-9">
<img src="pic_mountain.jpg" alt="Mountain View">
</div>
// mixin defenition
@mixin ratio($x, $y) {
display: block;
position: relative;
height: 0;
overflow: hidden;
padding-bottom: #{$y / $x * 100 + '%'};
img {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
}
// use mixin
.ratio-1-1 {
@include ratio(1, 1);
}
.ratio-16-9 {
@include ratio(16, 9);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment