如果图像高度超过图像宽度,通过裁剪其顶部和底部来垂直居中图像-仅使用CSS即可

If image height exceeds image width, vertically center image by cropping its top and bottom - possible with only CSS?

本文关键字:图像 垂直居中 底部 即可 CSS 高度 如果 裁剪 顶部      更新时间:2023-09-26

假设您事先不知道图像元素的高度和宽度,假设在图像高度大于图像宽度的情况下,您希望通过从顶部和底部裁剪相同数量的像素来垂直地将图像放在中间,以便新的图像高度与图像宽度匹配。例如,如果图像宽度为200px,高度为250px,则从其顶部和底部各裁剪25px。

下面是一个示例设置:

HTML:

<div class = 'cell'>
  ...
  <div class = 'image_container'> 
     ... 
     <img ...> 
  </div>
</div>
CSS:

.cell {
    display: inline-block;
    float: left;
    /* width will be changed by use of '@media screen'.
       Smaller browser window -> larger width */
    width: 31%;
}
.image_container {
    position: relative;
    float: left;
    width: 100%;
}
.image_container > img {
    width: 100%;
}

是否有可能完成上述中心/裁剪操作仅使用CSS,还是有必要使用javascript/jquery ?

可以使用object-fit的CSS属性。它的作用很像background-size属性。

.image_container > img {
    object-fit: contain;
}

请注意,到目前为止(2016年10月),这还没有完全的浏览器支持,所以你可能想看看将图像设置为div的背景,并使用background-positionbackground-size来处理这个问题,而不是<img>标签。

.image_container {
  height: 300px;
  background-color: cornflowerblue;
  image-rendering: pixelated;
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAALklEQVQoU2NkgID/UBqdYmSESoJobOA/sgKQKTCFMDaKAuqYAHMs3CqiHInXmwDZGBMDEmk6SQAAAABJRU5ErkJggg==');
  background-repeat: no-repeat;
  background-position: center center;
  background-size: 200px;
}
<div class="image_container"></div>

.cover_image {
  height: 400px;
  background: url('http://lorempixel.com/g/400/200/') no-repeat scroll center center;
  background-size: cover;
}
<div class="cover_image"></div>