简体   繁体   English

将div中的图像垂直对齐到中间

[英]Align image inside div to the middle vertically

I have an image inside a div. 我在div内有一张图片。 I crop the image by having a fixed height on the div and overflow: hidden . 我通过在div上固定高度来裁剪图像并overflow: hidden How do I align the image inside to the middle vertically ? 如何将内部的图像垂直对齐到中间?

So, to visualize my aim: 因此,将我的目标形象化:

在此处输入图片说明

  1. Full image of cat. 猫的完整图像。

  2. How it is currently looking when the image is cropped. 裁剪图像时当前的外观。

  3. How I want it to look. 我希望它看起来如何。 The image is aligned to the middle vertically and cropped accordingly. 图像在垂直方向上与中间对齐,并进行相应的裁剪。

Please note that the height of the image varies (user uploaded). 请注意,图像的高度会有所不同(用户上传)。

jsFiddle for testing. jsFiddle进行测试。

HTML: HTML:

<div class="container">
    <img src="http://i.imgur.com/qRkEJni.jpg">
</div>

CSS: CSS:

.container {
    height:200px;
    width:200px;
    float:left;
    overflow: hidden;
}

.container img{
    height:auto;
}

Here is an alternate way: 这是另一种方法:

.container img {
    height: auto;
    top: 50%;
    position: relative;
    transform: translate(0,-50%);
}

JSFiddle JSFiddle

Flexbox can do that: Flexbox可以做到这一点:

 .container { height:200px; width:200px; float:left; overflow: hidden; border:1px solid black; display: flex; flex-direction: column; justify-content: center; } .container img{ height:auto; display: block; } 
 <div class="container"> <img src="http://i.imgur.com/qRkEJni.jpg"> </div> 

or absolute positioning. 或绝对定位。

 .container { height: 200px; width: 200px; float: left; overflow: hidden; border: 1px solid black; position: relative; } .container img { height: auto; position: absolute; top: 50%; left: 0; transform: translateY(-50%); } 
 <div class="container"> <img src="http://i.imgur.com/qRkEJni.jpg"> </div> 

Or...of course, using a background image instead. 或者...当然,可以使用背景图片代替。

 .container { height: 200px; width: 200px; float: left; overflow: hidden; border: 1px solid black; position: relative; background-image: url(http://i.imgur.com/qRkEJni.jpg); background-position: center center; } 
 <div class="container"> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM