我正在尝试创建一个简单的类似画廊的图像查看器,并且我想将图像与页面的中心和中间对齐。
这可以简单地使用 table
和 table-row
来完成,但仅限于图像小于页面 100% 的情况。在第二种情况下,我可以简单地通过 text-align: center
和 max-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>
但是如何让它在这两种情况下都正常工作?
最佳答案
您可以像这样使用 flexbox :
.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:absolute
和transform
,如下所示:
.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>
关于CSS 将全屏图像与最大高度对齐到中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31752173/