Last active
November 22, 2016 20:55
-
-
Save jhogue/d5e23237ffdcdebf9c84f296ecdd46a7 to your computer and use it in GitHub Desktop.
Responsive image Aspect Ratio with calc()
This file contains 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
// Intent: | |
// Create a calc() function that dynamically changes the padding-bottom | |
// value for a container than wraps an image to force an aspect ratio. | |
// For small viewports, the padding bottom value is 56.25% for a 16:9 ratio | |
// For larger, it goes down to 25% for a really wide, thin image | |
// This is the way I do it now: | |
@mixin maintain-ratio($ratio: 1 1) { | |
@if length($ratio) < 2 or length($ratio) > 2 { | |
@warn "$ratio must be a list with two values."; | |
} | |
height: 0; | |
padding-bottom: percentage(nth($ratio, 2) / nth($ratio, 1)); | |
width: 100%; | |
} | |
.rwd-img-wrapper { | |
@include maintain-ratio( 16 9 ); // 56.25% | |
overflow: hidden; | |
position: relative; | |
z-index: 1; | |
img { | |
height: auto; | |
position: absolute; | |
top: 50%; left: 0; | |
width: 100%; | |
z-index: 2; | |
} | |
// Make thinner for larger screens | |
@media (min-width: 480) { | |
padding-bottom: percentage(9 / 21); // 42.85% | |
} | |
@media (min-width: 700) { | |
padding-bottom: percentage(6 / 16); // 37.5% | |
} | |
@media (min-width: 960) { | |
padding-bottom: percentage(1 / 3); // 33.33% | |
} | |
@media (min-width: 1200) { | |
padding-bottom: percentage(1 / 4); // 25% | |
} | |
} | |
// Using magic similar to this http://blog.typekit.com/2016/08/17/flexible-typography-with-css-locks/ | |
// I'd like to use calc() to dynamically move between a top "gate" of 56.25% | |
// down to 25%, as the width of the viewport increases | |
// Any takers? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment