Search code examples
htmlcssvertical-alignmentviewport-units

Centering an image vertically in a div with a dynamic height


I have a div that is 1/5 the vh of the screen. I want the image within that div to be centered vertically. I am able to center it horizontally but have tried the following code thus far:

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>


Solution

  • You can give the parents divs relative positioning and the images absolute positioning:

    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>