Skip to main content

Helpers

Ratios

Use the aspect-ratio helper to make an element keep the aspect ratio of your choosing. Perfect for responsively handling video or slideshow embeds based on the width of the parent.

View page source on GitHub

About#

Use the ratio helper to manage the aspect ratios of external content like <iframe>s, <embed>s, <video>s, and <object>s. These helpers also can be used on any standard HTML child element (e.g., a <div> or <img>). Styles are applied from the parent .ratio class directly to the child.

The ratio is held in a CSS variable, --ratio, and applied with the CSS aspect-ratio property, which also allows custom aspect ratios.

Example#

Wrap any embed, like an <iframe>, in a parent element with .ratio and an aspect ratio class. The immediate child element is automatically sized thanks to the universal selector .ratio > *.

<div class="ratio ratio-16x9">
  <iframe src="https://www.youtube.com/embed/zpOULjyy-n8?rel=0" title="YouTube video" class="border-0" allowfullscreen></iframe>
</div>

Aspect ratios#

Aspect ratios can be customized with modifier classes. By default the following ratio classes are provided:

1x1
4x3
16x9
21x9
<div class="ratio ratio-1x1">
  <div>1x1</div>
</div>
<div class="ratio ratio-4x3">
  <div>4x3</div>
</div>
<div class="ratio ratio-16x9">
  <div>16x9</div>
</div>
<div class="ratio ratio-21x9">
  <div>21x9</div>
</div>

Custom ratios#

Each .ratio-* class sets the --ratio custom property. You can set it yourself to create custom aspect ratios on the fly, written like the aspect-ratio property: width, slash, height.

For example, to create a 2x1 aspect ratio, set --ratio: 2 / 1 on the .ratio.

2x1
<div class="ratio" style="--ratio: 2 / 1;">
  <div>2x1</div>
</div>

This CSS variable makes it easy to modify the aspect ratio across breakpoints. The following is 4x3 to start, but changes to a custom 2x1 at the medium breakpoint.

@media (min-width: 768px) {
  .ratio-4x3 {
    --ratio: 2 / 1;
  }
}
4x3, then 2x1
<div class="ratio ratio-4x3">
  <div>4x3, then 2x1</div>
</div>

Bootstrap's --bs-aspect-ratio takes a padding percentage (50% for 2x1); felt-css's --ratio takes a ratio (2 / 1).