首页 > 解决方案 > 无论大小和格式如何,在 div 中居中图像而不拉伸它

问题描述

使用我的代码,我将图像置于 div 的中心。此解决方案适用于方形或横向格式的图像,但不适用于纵向格式的图像。

HTML 如下所示:

<div class="gallery"><img class="gallery"></div>

这是我的 CSS:

div.gallery {

 position: relative;
 z-index: 2;
 overflow: hidden;

}

img.gallery {

 height:100%;
 min-width: 100%;

 position: absolute;
 top:    -9999px;
 bottom: -9999px;
 left:   -9999px;
 right:  -9999px;
 margin: auto;

 box-sizing: border-box;
 z-index: 1;

}

我试着把 img.gallery 放在

min-width: 100%;
max-width: 100%;

但这并不能胜任工作,因为图片在 div 中太大了。有人对我有线索吗?

标签: css

解决方案


我相信以下方法可以解决您的问题。position: absolute我使用and将图像居中在 div 内transform: translate,并overflow: hidden隐藏溢出的内容。

div.gallery {
  height: 100px;
  width: 100px;
  border: 1px solid black;
  position: relative;
  z-index: 2;
  overflow: hidden;
}

img.gallery {
  height: auto;
  width: auto;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="gallery">
  <img src="http://via.placeholder.com/1000x1000" class="gallery">
</div>


推荐阅读