如何均匀设置弹性项高度

时间:2017-09-09 06:44:11

标签: html css image css3 flexbox

我有一个弹性箱容器和两个弹性箱子项:item-imgitem-contentitem-img中有一张图片。我希望item-img的高度等于item-content的高度,图像将覆盖它的所有空间。

这意味着item-img的高度设置为基于 item-content的高度。 item-content的高度不固定,可能比图像的高度大得多或小得多。

任何帮助将不胜感激。非常感谢。



.flex-container {
  display: flex;
  width: 500px;
  border: solid 1px #123;
}

.flex-item {
  max-width: 50%;
  overflow: hidden;
  flex-basis: 50%;
}

.item-img {
  display: flex;
}

img {
  object-fit: cover;
}

<div class="flex-container">
  <div class="flex-item item-img">
    <img src="http://via.placeholder.com/350x350">
  </div>
  <div class="flex-item item-content">
    <p>This is conent with text</p>
    <p>more text</p>
    <p>more text</p>
    <p>more text</p>
    <p>more text</p>
    <p>more text</p> 
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

height: 100%max-width: 100%设置为img并将图片绝对放在item-img内(以便容器始终占据item-content) - 见下面的演示:

.flex-container {
  display: flex;
  width: 500px;
  border: solid 1px #123;
}

.flex-item {
  max-width: 50%;
  overflow: hidden;
  flex-basis: 50%;
}

.item-img {
  display: flex;
  position: relative;
}

img {
  /*object-fit: cover;*/
  height: 100%;
  max-width: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
<div class="flex-container">
  <div class="flex-item item-img">
    <img src="http://via.placeholder.com/350x350">
  </div>
  <div class="flex-item item-content">
    <p>This is content with text</p>
    <p>more text</p>
    <p>more text</p>
    <p>more text</p>
    <p>more text</p>
    <p>more text</p> 
  </div>
</div>

<br/><br/>

<div class="flex-container">
  <div class="flex-item item-img">
    <img src="http://via.placeholder.com/50x50">
  </div>
  <div class="flex-item item-content">
    <p>This is content with text</p>
    <p>more text</p>
    <p>more text</p>
    <p>more text</p>
    <p>more text</p>
    <p>more text</p> 
  </div>
</div>

编辑:为img定位添加容器以及object-fit: coverwidth: 100% {{1}下面的演示:

img
.flex-container {
  display: flex;
  width: 500px;
  border: solid 1px #123;
}

.flex-item {
  max-width: 50%;
  overflow: hidden;
  flex-basis: 50%;
}

.item-img {
  display: flex;
  position: relative;
}

.item-img div {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

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