简体   繁体   中英

css3 flex: why img take more width than contains?

在此处输入图像描述

  1. Why .itm in this case take width 400px instead of 160px ? In other cases div take same width like child, but when img is bigger and browser scale it - I got empty space

  2. How to fix it? I fount only one way: set <img height="..." width="..." /> , but I want more more suitable way because I don't know real image size.

 .box { display: flex; }.box.itm { max-height: 400px; max-width: 400px; background: red; margin-right: 10px; }.box.itm img { max-height: 100%; max-width: 100%; }.box.itm.tst { width: 160px; height: 400px; background: lime; }
 <div class="box"> <div class="itm"> <img src="https://picsum.photos/300/750"/> </div> <div class="itm"> <div class="tst">same block with 160x400 sime like img</div> </div> </div>

Problem

As the flex items do not have width or flex-basis properties defined, flex container space distributed as first element will take the max-width size, and the second item will take the remaining space.

Solution

Add width and flex-basis properties to flex items

  1. I didn't understand why this is happening

  2. I fixed this by moving the max-width directly to each image. In my case, this solves the problem, but it would not help if there was not only a picture but also other content in the container.

 .box { display: flex; }.box.itm { display: flex; background: red; margin-right: 10px; }.box.itm img { max-height: 400px; max-width: 400px; }.box.itm.tst { width: 160px; height: 400px; background: lime; }
 <div class="box"> <div class="itm"> <img src="https://picsum.photos/300/750"/> </div> <div class="itm"> <div class="tst">same block with 160x400 sime like img</div> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM