【问题标题】:Img using `object-fit: cover` still increases height of parent使用 `object-fit: cover` 的 Img 仍然会增加父级的高度
【发布时间】:2020-11-20 08:57:41
【问题描述】:

我正在构建一个内容可变的组件。所以我希望 img 像 bg img 一样响应,取其容器的高度而不是定义高度。即使我定义了 add object-fit: cover,img 仍然会影响其父级的高度。我希望文本定义父级的高度,而不是 img。我不希望使用背景图像,因为图像是通过所见即所得编辑器填充的,并且我无法控制上传的图像的加载位置(即它必须是图像)。感谢您的帮助。

Codesandbox

代码:

.container {
    display: flex;
    flex-direction: row;
    padding: 20px;
    background: lightblue;
    width: 80%;
}

.img-item {
    align-self: stretch;
    flex-shrink: 2;
}

.img-item img {
    object-fit: cover;
    height: 100%;
    width: 100%;
}

.text-item {
    flex-shrink: 3;
    padding: 20px;
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Static Template</title>
        <link rel="stylesheet" href="style.css" />
    </head>
    <body>
        <div class="container">
            <div class="img-item">
                <img src="https://i.imgur.com/2bvab7y.jpg" alt="" />
            </div>
            <div class="text-item">
                <h1>
                    Heading one
                </h1>
                <p>Hello world. You're the best.</p>
            </div>
        </div>
    </body>
</html>

【问题讨论】:

    标签: html css layout flexbox object-fit


    【解决方案1】:

    你不见了the flex-basis CSS property

    .container {
      display: flex;
      flex-direction: row;
      padding: 20px;
      background: lightblue;
      width: 80%;
    }
    .img-item {
      align-self: stretch;
      flex-shrink: 2;
    }
    .img-item img {
      object-fit: cover;
      height: 100%;
      width: 100%;
    }
    .text-item {
      flex-shrink: 3;
      padding: 20px;
    }
    [class$=item]{flex-basis: 120px;}
    <div class="container">
      <div class="img-item">
        <img src="https://i.imgur.com/2bvab7y.jpg" alt="" />
      </div>
      <div class="text-item">
        <h1>
          Heading one
        </h1>
        <p>Hello world. You're the best.</p>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-26
      • 2019-08-30
      • 2016-02-24
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      相关资源
      最近更新 更多