在具有动态高度的 div 中垂直居中图像

Centering an image vertically in a div with a dynamic height

我有一个 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>

您可以给 parents 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;
}
<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>

couple of ways 可以实现这一点,但是可以通过为 line-height 设置相同的值并通过 vertical-align: middle 声明在中间垂直对齐图像来实现,如下所示:

Example Here.

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;
}
<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>

DEMO

将 position:relative 添加到容器中。

.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%);
}