已知宽度,高度怎么设置为宽度的百分比

157 阅读1分钟

要将一个元素的高度设置为其宽度的 80%,可以使用 CSS 的 aspect-ratio 属性(支持较新的浏览器)或使用 padding-top 技巧。下面是这两种方法的示例:

方法 1:使用 aspect-ratio(宽高比:也可以一直高度设置宽度---浏览器兼容性差)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
      .box {
          width: 200px;
          aspect-ratio: 5 / 4; /* 高度为宽度的 80% (即 4 / 5 = 0.8) */
          background-color: lightblue; /* 方便查看效果 */
      }
  </style>
</head>
<body>
<div class="box"></div>
</body>
</html>

方法 2:使用 padding-top 技巧(推荐使用)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
      .container {
          width: 200px;
          position: relative;
      }

      .box {
          width: 100%; /* 使子元素宽度填满父容器 */
          padding-top: 80%; /* 高度为宽度的80% */
          background-color: lightblue; /* 方便查看效果 */
          position: relative;
      }

      .box::before {
          content: "";
          display: block;
          width: 100%; /* 填满父元素 */
          height: 100%; /* 填满父元素 */
          background-color: lightcoral; /* 方便查看效果 */
      }
  </style>
</head>
<body>
<div class="container">
  <div class="box"></div>
</div>
</body>
</html>

说明

  • aspect-ratio 方法非常直观,但需确保浏览器支持。
  • padding-top 方法依赖于元素的相对定位,通过 padding-top 来实现比例,高度是由内边距创建的,适用于所有现代浏览器。