关键词:固定长宽比

在 CSS 中,可以通过以下几种方式实现固定长宽比的元素:

一、使用 padding 实现

  1. 原理:

    • 利用元素的padding属性以百分比形式设置时是相对于父元素宽度的特点,通过设置padding-toppadding-bottom来实现固定的长宽比。
  2. 示例代码:

     1<div class="aspect-ratio-box">
     2  <!-- 这里可以放置内容 -->
     3</div>
     1.aspect-ratio-box {
     2  width: 100%;
     3  position: relative;
     4  padding-top: 56.25%; /* 16:9 的长宽比,9/16 = 0.5625,即 56.25% */
     5}
     6.aspect-ratio-box > * {
     7  position: absolute;
     8  top: 0;
     9  left: 0;
    10  width: 100%;
    11  height: 100%;
    12}
    • 在这个例子中,设置了一个容器元素,通过padding-top56.25%实现了 16:9 的长宽比。容器内的子元素通过绝对定位填充整个容器。

二、使用伪元素和vw单位实现

  1. 原理:

    • 利用伪元素::before::after,并设置其content属性为空,通过设置其heightwidth为相对于视口宽度(vw单位)的百分比来实现固定长宽比。
  2. 示例代码:

     1<div class="aspect-ratio-box-vw">
     2  <!-- 这里可以放置内容 -->
     3</div>
     1.aspect-ratio-box-vw {
     2  width: 100%;
     3  position: relative;
     4}
     5.aspect-ratio-box-vw::before {
     6  content: "";
     7  display: block;
     8  padding-top: 56.25%; /* 16:9 的长宽比 */
     9}
    10.aspect-ratio-box-vw > * {
    11  position: absolute;
    12  top: 0;
    13  left: 0;
    14  width: 100%;
    15  height: 100%;
    16}
    • 这个方法与第一种类似,但是使用了伪元素和padding-top相对于视口宽度的特点来实现长宽比。

三、使用 CSS Grid 实现

  1. 原理:

    • 通过 CSS Grid 布局,设置一个网格容器,并定义其中一个维度的大小,然后让另一个维度自动填充以实现固定长宽比。
  2. 示例代码:

     1<div class="aspect-ratio-grid">
     2  <!-- 这里可以放置内容 -->
     3</div>
     1.aspect-ratio-grid {
     2  width: 100%;
     3  height: 0;
     4  padding-bottom: 56.25%; /* 16:9 的长宽比 */
     5  display: grid;
     6}
     7.aspect-ratio-grid > * {
     8  grid-row: 1;
     9  grid-column: 1;
    10}
    • 在这个例子中,设置容器的padding-bottom56.25%来实现 16:9 的长宽比,然后使用 CSS Grid 布局将子元素放置在网格的第一个单元格中。
个人笔记记录 2021 ~ 2025