Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responsive vertical center with overflow hidden

After searching both Stack Overflow and Google I still wonder how to vertical center a image that is bigger than it's parent element. I use no height, just max-height, because I want to make a responsive solution, without jQuery. If possible.

Here is some code:

<div style="max-height: 425px; overflow: hidden;">
    <img src="http://img.youtube.com/vi/jofNR_WkoCE/maxresdefault.jpg">
</div>
like image 942
Henrik Albrechtsson Avatar asked Nov 22 '13 09:11

Henrik Albrechtsson


2 Answers

I found a way to make it work with only a max-height (as opposed to a fixed height) set on the container.

The bad news is that it requires an additional wrapper element.

HTML:

<div class="img-wrapper">
    <div class="img-container">
        <img src="http://img.youtube.com/vi/jofNR_WkoCE/maxresdefault.jpg">
    </div>
</div>

CSS:

.img-wrapper {
    overflow: hidden;
    max-height: 425px;
}

.img-container {
    max-height: inherit;
    transform: translateY(50%);
}

.img-wrapper img {
    display: block;
    transform: translateY(-50%);
}
like image 24
Thomas Bachem Avatar answered Oct 04 '22 20:10

Thomas Bachem


to center vertically an bigger image u can use the construction and css bellow

<div class="img-wrapper">
    <img src="http://img.youtube.com/vi/jofNR_WkoCE/maxresdefault.jpg">
</div>

And css:

.img-wrapper{
    position: relative;
    overflow:hidden;
    height:425px;
}

.img-wrapper img{
    position: absolute;
    top:-100%; left:0; right: 0; bottom:-100%;
    margin: auto;
}

FIDDLE

like image 124
Alexandru Diacov Avatar answered Oct 04 '22 21:10

Alexandru Diacov