Skip to main content Skip to docs navigation

比率

使用生成的伪元素使元素保持你选择的纵横比。非常适合根据父级的宽度响应式处理视频或幻灯片嵌入。

关于

¥About

使用比例助手来管理外部内容的宽高比,例如 <iframe><embed><video><object>。这些助手还可以用于任何标准 HTML 子元素(例如 <div><img>)。样式从父 .ratio 类直接应用于子类。

¥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.

长宽比在 Sass 映射中声明,并通过 CSS 变量包含在每个类中,这也允许 自定义宽高比

¥Aspect ratios are declared in a Sass map and included in each class via CSS variable, which also allows custom aspect ratios.

Pro-Tip! You don’t need frameborder="0" on your <iframe>s as we override that for you in Reboot.

示例

¥Example

将任何嵌入(如 <iframe>)封装在具有 .ratio 和宽高比类的父元素中。由于我们的通用选择器 .ratio > *,直接子元素会自动调整大小。

¥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 our universal selector .ratio > *.

html
<div class="ratio ratio-16x9">
  <iframe src="https://www.youtube.com/embed/zpOULjyy-n8?rel=0" title="YouTube video" 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
html
<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

每个 .ratio-* 类在选择器中都包含一个 CSS 自定义属性(或 CSS 变量)。你可以覆盖此 CSS 变量,通过一些快速数学运算即时创建自定义宽高比。

¥Each .ratio-* class includes a CSS custom property (or CSS variable) in the selector. You can override this CSS variable to create custom aspect ratios on the fly with some quick math on your part.

例如,要创建 2x1 的宽高比,请在 .ratio 上设置 --bs-aspect-ratio: 50%

¥For example, to create a 2x1 aspect ratio, set --bs-aspect-ratio: 50% on the .ratio.

2x1
html
<div class="ratio" style="--bs-aspect-ratio: 50%;">
  <div>2x1</div>
</div>

此 CSS 变量可以轻松地跨断点修改纵横比。以下是 4x3 开始,但在中断点处更改为自定义 2x1。

¥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.

.ratio-4x3 {
  @include media-breakpoint-up(md) {
    --bs-aspect-ratio: 50%; // 2x1
  }
}
4x3, then 2x1
html
<div class="ratio ratio-4x3">
  <div>4x3, then 2x1</div>
</div>

Sass 映射

¥Sass maps

_variables.scss 中,你可以更改要使用的宽高比。这是我们默认的 $ratio-aspect-ratios 映射。根据需要修改映射并重新编译 Sass 以使用它们。

¥Within _variables.scss, you can change the aspect ratios you want to use. Here’s our default $ratio-aspect-ratios map. Modify the map as you like and recompile your Sass to put them to use.

$aspect-ratios: (
  "1x1": 100%,
  "4x3": calc(3 / 4 * 100%),
  "16x9": calc(9 / 16 * 100%),
  "21x9": calc(9 / 21 * 100%)
);