Twitter Bootstrap: Carousel: Vertically Center Image in Definded height Viewport

David Leonard picture David Leonard · Feb 1, 2013 · Viewed 26.8k times · Source

I am attempting to find a way to verticially center an image inside of my viewport for the carousel. Currently the images are working fine and it is resizing the image to the size of the viewport on the width. But I want to use the center of the image and crop the top and bottom of the photo.

Here is the HTML:

<div class="carousel slide hero">
   <div class="carousel-inner">
       <div class="active item">
            <img src="img/hero/1.jpg" />
       </div>
       <div class="item">
           <img src="img/hero/2.jpg" />
       </div>
       <div class="item">
           <img src="img/hero/3.jpg" />
       </div>
    </div>
    <a class="carousel-control left" href=".hero" data-slide="prev">&lsaquo;</a>
    <a class="carousel-control right" href=".hero" data-slide="next">&rsaquo;</a>
</div><!-- hero -->

and the small bit of css:

.carousel-inner {
    height: 320px;
    overflow: hidden;
}

Any help is greatly appreciated. I want it so that if they upload any size photo it can be considered usable.

Answer

Naragot picture Naragot · Feb 27, 2015

I have solved this problem by specifying the .item height and making the image in it absolutely positioned:

.item {
height: 300px;
}

.item img {
max-height: 100%;  
max-width: 100%; 
position: absolute;  
top: 0;  
bottom: 0;  
left: 0;  
right: 0;  
margin: auto;
}

This will make a carousel 300px height with images centered vertically and horizontally.