在保持Aspect Fit的同时,在div中垂直居中图像

时间:2017-05-12 14:33:46

标签: javascript html css

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

我创建了一个这样的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而是顶部对齐。

1 个答案:

答案 0 :(得分:1)

不是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>