javiertoledos of Creative Science Labs
10/6/2016 - 9:33 PM

Sass Mixin for keeping aspect ratio in responsive HTML elements

Sass Mixin for keeping aspect ratio in responsive HTML elements

@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;
    }
}

//Usage
@include aspect-ratio(4,3);

// Recomendations
// When using it in a <figure> the img will need to have an absolute positioning and 100% width.
// This is enough to make it responsive