Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Last active July 24, 2023 08:35
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jonathantneal/a9b8901273475d261dd3 to your computer and use it in GitHub Desktop.
Save jonathantneal/a9b8901273475d261dd3 to your computer and use it in GitHub Desktop.
Fluid Aspect: A Sass mixin for creating intrinsic ratios

Fluid Aspect

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]);
  • $ratio: An aspect ratio represented as two numbers separated by a space. Defaults to 1:1
  • $target: A selector targeting the element to be made fluid. Defaults to "> :first-child"

Usage

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%;
}
@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%;
}
}
@yairEO
Copy link

yairEO commented Feb 6, 2017

if you use the before or after selector, than you should add a content:'' property.
Maybe you can just add it regardless and be done with it.

@meowsus
Copy link

meowsus commented Mar 1, 2018

Well done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment