Responsive vertical center with overflow hidden

2019-03-09 11:09发布

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>

5条回答
够拽才男人
2楼-- · 2019-03-09 11:45

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

查看更多
smile是对你的礼貌
3楼-- · 2019-03-09 11:55

if you want to make a responsive image, try using
<div style="">
<img src="http://img.youtube.com/vi/jofNR_WkoCE/maxresdefault.jpg" width="100%" height="100%">
</div>

查看更多
我想做一个坏孩纸
4楼-- · 2019-03-09 12:02

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%);
}
查看更多
forever°为你锁心
5楼-- · 2019-03-09 12:07

Try

<html>
<head>
</head>
<body >

    <div style="max-height: 425px;border:1px solid;max-width:500px;overflow:hidden">
        <img src="http://img.youtube.com/vi/jofNR_WkoCE/maxresdefault.jpg" style='position: relative;top: -231px;left: -500px;'>
    </div>
</body>
</html>
查看更多
再贱就再见
6楼-- · 2019-03-09 12:08

If you dont need to use img tags (fiddle):

CSS

.imageContainer {
    margin: 0; 
    height: 200px; /* change it to your value*/
    width: 200px; /* or use fixed width*/
    background: transparent url('') no-repeat center;
    overflow: hidden; 
}

HTML

<div class="imageContainer" style="background-image: url('http://deepwish.com/site/wp-content/uploads/2013/10/butterfly2_large.jpg');"></div>
查看更多
登录 后发表回答