Fluid Aspect: A Sass mixin for creating intrinsic ratios
@mixin fluid-aspect($ratio: 1 1, $selector: "> :first-child") {
$selector: unquote($selector);
padding-bottom: percentage(nth($ratio, 2) / nth($ratio, 1));
position: relative;
#{$selector} {
left: 0;
height: 100%;
position: absolute;
top: 0;
width: 100%;
}
}
fluid-aspect is a Sass mixin for creating intrinsic ratios in CSS. Intrinsic ratios allow elements to fill the width of their containing block and resize on the fly while maintaining their aspect ratio.
@include fluid-aspect($ratio, [$target]);
Create a fluid aspect ratio container by including the mixin and its first child will by made fluid.
.my-container {
@include fluid-aspect(16 9);
}
Rendered as CSS:
.my-container {
padding-bottom: 56.25%;
position: relative;
}
.my-container > :first-child {
left: 0;
height: 100%;
position: absolute;
top: 0;
width: 100%;
}
Create a fluid container that specifies the descendant that will become fluid.
.my-container {
@include fluid-aspect(4 3, iframe);
}
Rendered as CSS:
.my-container {
padding-bottom: 75%;
position: relative;
}
.my-container iframe {
left: 0;
height: 100%;
position: absolute;
top: 0;
width: 100%;
}
Remember that advanced selectors must be wrapped in a string. Within a string, you can still reference parent selectors using the ampersand (&) character.
.my-container {
@include fluid-aspect(5 3, "&--fluid");
}
Rendered as CSS:
.my-container {
padding-bottom: 60%;
position: relative;
}
.my-container--fluid {
left: 0;
height: 100%;
position: absolute;
top: 0;
width: 100%;
}