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

时间:2015-03-27 17:23:39

标签: html css css3 vertical-alignment viewport-units

我的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;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

你可以给父母div相对定位和图像绝对定位:

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:1)

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

Example Here

&#13;
&#13;
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;
&#13;
&#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%);
}