繁体   English   中英

css3 flex:为什么 img 占用的宽度大于包含的宽度?

[英]css3 flex: why img take more width than contains?

在此处输入图像描述

  1. 为什么.itm在这种情况下采用宽度400px而不是160px 在其他情况下,div 像孩子一样采用相同的宽度,但是当 img 更大并且浏览器对其进行缩放时 - 我得到了空白空间

  2. 如何解决? 我只有一种方式:设置<img height="..." width="..." /> ,但我想要更合适的方式,因为我不知道真实的图像大小。

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

问题

由于弹性项目没有定义widthflex-basis属性,作为第一个元素分配的flex容器空间将占用max-width大小,第二个项目将占用剩余空间。

解决方案

为弹性项目添加widthflex-basis属性

  1. 我不明白为什么会这样

  2. 我通过将最大宽度直接移动到每个图像来解决这个问题。 就我而言,这解决了问题,但如果容器中不仅有图片而且还有其他内容,这将无济于事。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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