首先,不确定它是否相关,但我使用的是 Bootstrap 3。
因此,对于我页面的这一部分(下面还有更多内容),我将视口(viewport)高度设置为 100,其中两行各占该视口(viewport)的 50%。第一行是我试图在水平和垂直方向居中的图像。第二行是我试图水平居中并固定在底部的图像。 html 看起来像这样:
<div class='row vh-100'>
<div class='col-xs-12 col-sm-12 col-md-12 col-lg-12 height-100'>
<!-- tats -->
<div class='row height-50'>
<div class='col-xs-12 col-sm-12 col-md-12 col-lg-12 relative height-100'>
<img src='images/logo.png'
class='img-responsive block absolute center middle max-height-100'>
</div>
</div>
<!-- silhouette -->
<div class='row height-50'>
<div class='col-xs-12 col-sm-12 col-md-12 col-lg-12 relative height-100'>
<img src='images/silhouette.png'
class='img-responsive block absolute center bottom max-height-100'>
</div>
</div>
</div>
</div>
CSS 看起来像这样:
.block{
display: block;
}
.absolute{
position: absolute;
}
.relative{
position: relative;
}
.vh-100{
height: 100vh;
}
.vh-50{
height: 50vh;
}
.height-100{
height: 100%;
}
.height-50{
height: 50%;
}
.center{
margin-left: auto;
margin-right: auto;
}
.top{
top: 0%;
}
.middle{
top: 50%;
}
.bottom{
bottom: 0%;
}
.max-height-100{
max-height: 100%;
}
所以我遇到的是这样的:图像不会水平居中,除非我将它们的位置更改为相对位置。此外,第一张图片在整个页面内垂直居中,而不是其包含的 div。有什么想法吗?
最佳答案
绝对位置元素是这样居中的:
#element {
left:50%;
top:50%;
transform:translate(-50%,-50%);
}
(不要忘记为转换添加供应商:-webkit-transform 等)
另外,如果你知道绝对元素的宽度,你可以使用:
margin-left:-halfelemwidth;
margin-top:-halfelemheight;
这将有助于支持不支持 css 转换的旧浏览器
编辑:打字时太累了,下面的用户提醒我注意 margin-top 和 margin-left 应该是一半而不是全。
edit2:您也可以尝试这种方法。
对于具有高度的父级元素,使用:
display:table-cell;
vertical-align:middle;
text-align:center;
这可以在不离开容器的情况下使图像居中,并且没有相对和绝对元素。
关于html - 位置为 :absolute not centering inside parent div with position:relative 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26318059/