4

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

4

3 回答 3

2

您可以给父母 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>

于 2015-03-27T17:28:02.423 回答
1

几种方法可以实现这一点,但是可以通过为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;
}
<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>

于 2015-03-27T17:28:16.870 回答
1

演示

添加位置:相对于容器。

.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%);
}
于 2015-03-27T17:28:24.490 回答