Last active
June 8, 2016 11:30
-
-
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.
This file contains hidden or 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
/* 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%; | |
} |
This file contains hidden or 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
<!-- 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> |
This file contains hidden or 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
// 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