我的div是屏幕vh
的1/5。我希望该div中的图像垂直居中。我可以水平居中,但到目前为止尝试了以下代码:
http://jsfiddle.net/ws91188y/1/
img{
width:25px;
}
.container-fluid > div{
text-align:center;
height: calc(100vh/5);
}
.container-fluid > div:nth-child(odd){
background:yellow;
}

<div class="container-fluid">
<div><img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg"></div>
<div><img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg"></div>
<div><img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg"></div>
<div><img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg"></div>
<div><img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg"></div>
</div>
&#13;
答案 0 :(得分:1)
你可以给父母div相对定位和图像绝对定位:
img {
width:25px;
position:absolute;
margin:auto;
top:0;
bottom:0;
}
.container-fluid > div {
text-align:center;
height: calc(100vh/5);
position:relative;
}
.container-fluid > div:nth-child(odd) {
background:yellow;
}
&#13;
<div class="container-fluid">
<div>
<img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg">
</div>
<div>
<img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg">
</div>
<div>
<img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg">
</div>
<div>
<img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg">
</div>
<div>
<img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg">
</div>
</div>
&#13;
答案 1 :(得分:1)
有couple of ways可以实现这一目标,但是可以通过为line-height
设置相同的值并通过vertical-align: middle
声明对图像进行垂直对齐来实现,如下所示:
img{
width:25px;
vertical-align: middle;
}
.container-fluid > div {
text-align:center;
height: calc(100vh/5);
line-height: calc(100vh/5);
}
.container-fluid > div:nth-child(odd){
background:yellow;
}
&#13;
<div class="container-fluid">
<div><img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg"></div>
<div><img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg"></div>
<div><img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg"></div>
<div><img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg"></div>
<div><img src="http://lorempixel.com/output/food-h-g-164-166-5.jpg"></div>
</div>
&#13;
答案 2 :(得分:1)
<强> DEMO 强>
添加位置:相对于容器。
.container-fluid > div {
text-align:center;
height: calc(100vh/5);
position: relative;
}
然后在你的img上:
img {
width:25px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}