0

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

代码沙盒

代码:

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

4

1 回答 1

0

您缺少flex-basis CSS 属性

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

于 2020-07-30T15:55:44.837 回答