在 div 中垂直居中图像,同时保持宽高比拟合



我有一个非常大的图像集合(总是大于屏幕/浏览器窗口(。我的目标是在全屏浏览器中显示图像(就像一个相框,它们总是水平和垂直居中在div 中,并且它们是div 中的纵横适合。

我创建了一个这样的div:

<div id="main" style="display: flex; align-items: center; justify-content: center; overflow: hidden;"></div>

然后我在里面添加了一个图像,如下所示:

if (photoWidth >= photoHeight) { // if this is a landscape or square image
    div.innerHTML = "<img style='flex:none;' height=" + screenHeight +  " src=images/" + encodeURI(imgName) + "></img>";
} else { // else if portrait image 
    div.innerHTML = "<img style='flex:none;'  width=" + screenWidth +  " src=images/" + encodeURI(imgName) + "></img>";
}

所有这些都适用于横向或方形图像,但如果图像是纵向的,则它不会在div 中垂直居中,而是顶部对齐。

不是 100% 确定这是否是你想要的,但试一试,让我知道。

OP定义了纵向和横向图像可以裁剪,而方形图像不应裁剪。

肖像示例

使用background-size: cover;,裁剪图像。

body {
  margin: 0;
}
div {
  height: 100vh;
  background-image: url('http://unsplash.it/2400/3200/?image=50');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
}
<div></div>

景观示例

使用background-size: cover;,裁剪图像。

body {
  margin: 0;
}
div {
  height: 100vh;
  background-image: url('http://unsplash.it/3200/2400/?image=100');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
}
<div></div>

方形示例

使用background-size: contain;,不裁剪图像。

body {
  margin: 0;
}
div {
  height: 100vh;
  background-image: url('http://unsplash.it/3200/3200/?image=55');
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center center;
}
<div></div>

最新更新