CSS 将全屏图像与最大高度对齐到中间

CSS align fullscreen image with max-height to middle

我正在尝试创建一个类似画廊的简单图像查看器,我想将图像与页面的中心和中间对齐。

这可以简单地使用 tabletable-row 来完成,但仅限于图像小于页面 100% 的情况。在第二种情况下,我可以通过 text-align: centremax-height: 100%.

简单地对齐它

这是我的代码:https://jsfiddle.net/rtv393z7/

<div style="position: fixed; width: 100%; height: 100%; top: 0; left: 0; background-color: rgba(0,0,0,0.6);">
  <div style="width: 100%; height: 100%; text-align: center;">
    <img style="max-height: 100%; max-width: 100%; box-sizing: border-box; padding: 30px;" src="http://i.imgur.com/uRGZ0EE.jpg">
  </div>
</div>

但是如何让它在这两种情况下都起作用?

你可以像这样使用弹性框:

.flex-content{
  display: flex;
  align-items: center;
  justify-content: center;
}
<div style="position: fixed; width: 100%; height: 100%; top: 0; left: 0; background-color: rgba(0,0,0,0.6);">
  <div class="flex-content" style="width: 100%; height: 100%; text-align: center;">
    <img style="max-height: 100%; max-width: 100%; box-sizing: border-box; padding: 30px;" src="http://i.imgur.com/uRGZ0EE.jpg">
  </div>
</div>

Here a working JSFiddle example

或者您可以像这样使用 position: absolutetransform

.center-content {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
}
<div style="position: fixed; width: 100%; height: 100%; top: 0; left: 0; background-color: rgba(0,0,0,0.6);">
    <div  class="center-content"  style="width: 100%; text-align: center;">
        <img style="max-height: 100%; max-width: 100%; box-sizing: border-box; padding: 30px;" src="http://i.imgur.com/uRGZ0EE.jpg">
    </div>
</div>

另请注意,我从 .center-content 中删除了 height: 100% 内联样式。

Here the JSFiddle for this alternative

不足之处是上面的例子在 FF 中不起作用,我在 Chrome 中看到了。

所以我这样修复它:

.center-content {
    position: relative;    
}

img{    
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
}
<div style="position: fixed; width: 100%; height: 100%; top: 0; left: 0; background-color: rgba(0,0,0,0.6);">
    <div  class="center-content"  style="width: 100%; height: 100%;">
        <img style="max-height: 100%; max-width: 100%; box-sizing: border-box; padding: 30px;" src="http://i.imgur.com/uRGZ0EE.jpg">
    </div>
</div>

And here the JSFiddle