[英]css3 flex: why img take more width than contains?
Why .itm
in this case take width 400px
instead of 160px
?为什么.itm
在这种情况下采用宽度400px
而不是160px
? In other cases div take same width like child, but when img is bigger and browser scale it - I got empty space在其他情况下,div 像孩子一样采用相同的宽度,但是当 img 更大并且浏览器对其进行缩放时 - 我得到了空白空间
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.我只有一种方式:设置<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>
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.由于弹性项目没有定义width
或flex-basis
属性,作为第一个元素分配的flex
容器空间将占用max-width
大小,第二个项目将占用剩余空间。
Solution解决方案
Add width
and flex-basis
properties to flex items为弹性项目添加width
和flex-basis
属性
I didn't understand why this is happening我不明白为什么会这样
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.