首页 > 解决方案 > 如何拉伸 img 元素以占据其 div 的全部高度

问题描述

我有 2 个 div 包含不同纵横比的图像。我需要 image2 来填充它的 div(container2),所以它们都将具有相同的响应高度。

我试图设置对象匹配,但它不起作用。我不想为 img 元素设置显式高度,因为这不会使设计灵活。我尝试这样做是为了能够使图像库都具有相同的高度,而不管纵横比是多少。

.container-of-containers {
  display: flex;
}

.container1 {
  border: 2px red solid;
  width: 300px;
  margin-right: 20px;
}

.container2 {
  border: 2px red solid;
  width: 40%;
}

img {
  width: 100%;
  display: block;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <div class=container-of-containers>
    <div class="container1">
      <img src="https://images.unsplash.com/photo-1502307100811-6bdc0981a85b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=626&q=80" alt="" class="image1">
    </div>
    <div class="container2">
      <img src="https://cdn.pixabay.com/photo/2015/12/01/20/28/road-1072823__340.jpg" alt="" class="image2">
    </div>
  </div>
</body>

</html>

那么,关于如何使这些 div 具有相同的高度而不在 img 元素上明确设置的任何想法?

标签: css

解决方案


将 img 包装在 2 个 div 中的答案。将 img 元素设置为绝对位置。根据https://www.w3schools.com/howto/howto_css_aspect_ratio.asp将第一个 div 父级设置为相对位置,并将 padding-top 设置为所需的百分比,以保持所需的纵横比。将第二个 div 父级设置为所需的宽度并将其浮动到左侧。

代码如下所示:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Setting the same height on 2 different aspect ratio images </title>
  <style>

    .aspect-ratio-outer {
      width: 50%;     /* Any width here applicable according to the design */
      float: left;    /* to align the containers of the images horizontally */
    }

    .aspect-ratio-inner{ 
      padding-top: 56.25%;  /* 19:6 aspect ratio */
      position: relative;   /* to allow absolute position for the child img */
    }

    img {
      width: 100%;   /* in order not to go out of its container */
      display: block;
      object-fit: cover;  /* to keep the aspect ratio of the source image not the aspect ratio we design here */
      height: 100%;    /* in order to fill its container height which is the padding-top we set */
    }

    .aspect-ratio-inner .image {
      position: absolute;  /* To make it always appear in its container */
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
    }

  </style>
</head>
<body>
    <div class="aspect-ratio-outer">
      <div class="container1 aspect-ratio-inner">
        <img src="https://images.unsplash.com/photo-1502307100811-6bdc0981a85b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=626&q=80" alt="" class="image">
      </div>
    </div>
    <div class="aspect-ratio-outer">
      <div class="container2 aspect-ratio-inner">
        <img src="https://cdn.pixabay.com/photo/2015/12/01/20/28/road-1072823__340.jpg" alt="" class="image">
      </div>
    </div>
</body>
</html>

推荐阅读