How to fit flex item's width to content image in flexbox? [duplicate]

放肆的年华 提交于 2020-08-08 05:35:51

问题


There is a <div> with display: flex;, flex-direction: column and fixed height and width. There are flex items containing images. After applying min-height: 0, as required, the images distributed vertically equal. But the flex items have some extra space left out. I can't remove this.

I tried all kind of stuff but no luck. please help.

.a {
  border: 1px red solid;
  width: 200px;
  height: 110px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.a>div {
  border: 1px blue solid;
  min-height: 0;
}

.a>div>img {
  height: 100%;
}
<div class="a">
  <div>
    <img src="https://via.placeholder.com/150.png" />
  </div>
  <div>
    <img src="https://via.placeholder.com/150.png" />
  </div>
  <div>
    <img src="https://via.placeholder.com/150.png" />
  </div>
</div>

回答1:


Just add height: calc(100% / 3) to .a > div.

Edit: Works on Firefox also.

.a {
  border: 1px red solid;
  width: 200px;
  height: 110px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.a > div {
  border: 1px blue solid;
  min-height: 0;
  height: calc(100% / 3); /* 3 is flex items in flex container */
  box-sizing:border-box;
}

.a > div > img {
  height: 100%;
}
<div class="a">
  <div>
    <img src="https://via.placeholder.com/150.png" />
  </div>
  <div>
    <img src="https://via.placeholder.com/150.png" />
  </div>
  <div>
    <img src="https://via.placeholder.com/150.png" />
  </div>
</div>



回答2:


Fiddling with your post, And I don't know why but adding height:100% to your flex items worked.

So yeah solution is to add height:100% in the flex items.

.a {
  border: 1px red solid;
  width: 200px;
  height: 110px;
  display: flex;
  flex-direction: column;
  align-items:flex-start;
  flex-grow:0;
}

.a>div {
  border: 1px blue solid;
  min-height: 0;
  height:100%;
}

.a>div>img {
height:100%
}
<div class="a">
  <div>
    <img src="https://via.placeholder.com/150.png" />
  </div>
  <div>
    <img src="https://via.placeholder.com/150.png" />
  </div>
  <div>
    <img src="https://via.placeholder.com/150.png" />
  </div>
</div>


来源:https://stackoverflow.com/questions/62920306/how-to-fit-flex-items-width-to-content-image-in-flexbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!