我正在尝试使用flex来简单地将一个img垂直居中在div中,但它在每个浏览器中的工作方式都不同.
.flex-container { display: -webkit-Box; display: -moz-Box; display: -ms-flexBox; display: -webkit-flex; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; justify-content: flex-start; } .flex-item { height: 222px; width: 200px; border: 1px solid lightgray; padding: 5px; margin: 5px; } .flex-item img { max-width: 100%; max-height: 100%; align-self: center; -webkit-align-self: center; margin: auto; } .item-image { border: 1px solid lightgray; display: -webkit-Box; display: -moz-Box; display: -ms-flexBox; display: -webkit-flex; display: flex; width: 190px; height: 120px; }
<div class="flex-container"> <div class="flex-item"> <div class="item-image"> <img src="https://c1.staticflickr.com/9/8264/8700922582_d7b50280b4_z.jpg"> </div> </div> </div>
https://jsfiddle.net/e0m2d6hx/
它在Chrome中很好,但在IE和FF中看起来它不适用于max-width.
谁能帮我这个?我知道我可以在没有flex的情况下将img居中,但我想了解这一点.
解决方法
如何修复IE和Firefox
以下更改应在Chrome,Firefox和IE中产生相同的结果:
>添加flex:0 0 auto;到.flex-item img.这修复了IE
>添加对象适合:缩小;到.flex-item img.这修复了Firefox
.flex-container { display: -webkit-Box; display: -moz-Box; display: -ms-flexBox; display: -webkit-flex; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; justify-content: flex-start; } .flex-item { height: 222px; width: 200px; border: 1px solid lightgray; padding: 5px; margin: 5px; } .flex-item img { flex: 0 0 auto; max-width: 100%; max-height: 100%; align-self: center; -webkit-align-self: center; margin: auto; object-fit: scale-down; } .item-image { border: 1px solid lightgray; display: -webkit-Box; display: -moz-Box; display: -ms-flexBox; display: -webkit-flex; display: flex; width: 190px; height: 120px; }
<div class="flex-container"> <div class="flex-item"> <div class="item-image"> <img src="http://www.joshuacasper.com/contents/uploads/joshua-casper-samples-free.jpg"> </div> </div> <div class="flex-item"> <div class="item-image"> <img src="https://c1.staticflickr.com/9/8264/8700922582_d7b50280b4_z.jpg"> </div> </div> <div class="flex-item"> <div class="item-image"> <img src="http://www.pinaldave.com/bimg/ilovesamples.jpg"> </div> </div> <div class="flex-item"> <div class="item-image"> <img src="http://appslova.com/wp-content/uploads/2014/11/Android-.png"> </div> </div> </div>
JS小提琴:https://jsfiddle.net/7yyf3nob/
为什么会这样?
不幸的是,我无法解释为什么浏览器之间的结果是如此不同,除了在IE和Firefox中使用flexBox模型时,img的自然调整大小属性会丢失. flexBox仍然是一个相对较新的模型,供应商仍在改进他们的实现.