Give embedded content and block elements a fixed aspect ratio, from a set of ratios or a custom property.
Overview
Ratio utilities set the CSS aspect-ratio property of an element, so its height follows its width. They suit embedded content such as <iframe>, <embed>, <video>, and <object> elements, and work on any other element, such as a <div> or an <img>. The $aspect-ratios Sass map holds the available ratios.
An <iframe> needs no frameborder="0" attribute: Reboot removes its border.
Example
Add a .ratio-{ratio} class to the element itself, an <iframe> or a <video> for example. The class sets no width, so pair it with a width utility such as .w-100.
<iframe class="w-100 ratio-16x9" src="https://www.youtube.com/embed/LO2RPDZkY88?rel=0" title="YouTube video" allowfullscreen></iframe>The classes cover 1x1, 4x3, 16x9, and 21x9, and .ratio-auto for the auto value.
<div class="ratio-auto">
<div>Auto</div>
</div>
<div class="w-25 ratio-1x1">
<div>1×1</div>
</div>
<div class="w-50 ratio-4x3">
<div>4×3</div>
</div>
<div class="w-75 ratio-16x9">
<div>16×9</div>
</div>
<div class="w-100 ratio-21x9">
<div>21×9</div>
</div>Custom ratios
A .ratio-* class sets the --cx-aspect-ratio custom property, and every element with such a class reads its aspect-ratio from it. Override the property for a ratio outside the set: --cx-aspect-ratio: 2 on a .ratio-auto element gives a 2x1 ratio.
<div class="w-25 ratio-auto" style="--cx-aspect-ratio: 2;">
<div>2x1</div>
</div>A media query that sets the custom property changes the ratio at a breakpoint. The example starts at 4x3 and switches to a custom 2x1 at the md breakpoint.
<div class="w-25 ratio-4x3">
<div>4x3, then 2x1</div>
</div>CSS
Ratio utilities are generated from Sass maps via the utilities API.
Reference
The table lists all ratio utilities and their CSS properties.
| Class | Properties |
|---|---|
.ratio-auto | --cx-aspect-ratio: auto; |
.ratio-1x1 | --cx-aspect-ratio: 1 / 1; |
.ratio-4x3 | --cx-aspect-ratio: 4 / 3; |
.ratio-16x9 | --cx-aspect-ratio: 16 / 9; |
.ratio-21x9 | --cx-aspect-ratio: 21 / 9; |
Sass maps
$aspect-ratios in scss/config/_defaults.scss holds the ratios; add an entry to generate another class.
$aspect-ratios: (
"auto": auto,
"1x1": #{"1 / 1"},
"4x3": #{"4 / 3"},
"16x9": #{"16 / 9"},
"21x9": #{"21 / 9"}
);Utilities API
Ratio utilities are declared in scss/utilities/_index.scss using the utilities API.
"aspect-ratio-attr": (
selector: "attr-includes",
class: "ratio-",
property: aspect-ratio,
values: var(--aspect-ratio),
),
"aspect-ratio": (
// property: aspect-ratio,
property: --aspect-ratio,
class: ratio,
values: $aspect-ratios
),