Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
941 views
in Technique[技术] by (71.8m points)

html - Image flex item does not shrink height in a flexbox

I have a flex container which contains an img flex item.

I want this img to disregard its intrinsic height (90px) so that the height may shrink to match the sibling's flex item height (as per the default align-items: stretch style).

.container {
    border: 1px solid;
    display: flex;
}

.item {
    border: 1px solid;
}

.content {
    width: 200px;
    height: 50px;
    background-color: hotPink;
}
<div class="container">
    <img class="item" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRu-3yBSd2b6JCOMcGVSOFf8X49QB3Ik-OI87gKEMwWLrdJxP5qOErmZQ">
    <div class="item">
        <div class="content"></div>
    </div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you are looking at this the wrong way.

The image itself is 90px high which means the content of the flex item has a height of 90px(because your image is the flex item). So your div on the right side is matching the image height because it is higher than the div's height and not the other way around.

Think of it as if you have set the height of the flex item(image) to 90px. So it won't shrink pass it unless you set it to a smaller height. Even though you didn't explicitly set the image height to 90px but it is 90px naturally so it is implicitly set which causes the confusion. So while it will stretch beyond 90px in height it won't go under it because that's the height of the flex item content.

In the case where you swapped it for a div and it works like you imagined is because there is no height set on the .item div which is the flex item.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...