这个:vertical centering working great 代码:
` <div class="container">
<h1>Vertical center with only 3 lines of code</h1>
<section class="text">
<p>I'm vertically aligned! Hi ho Silver, away!</p>
</section>
</div>`
但是,如果我尝试通过
使用相同的方法水平居中left: 50%; translateX(-50%);
在 CSS 的 .container 元素中取消注释两行之后 我得到奇怪的结果:容器水平居中,但垂直居中丢失。 我在这里缺少什么,以及如何实现我想要的:通过 translateX/Y 将容器在页面上垂直和水平居中?
最佳答案
它不起作用的原因是后一个属性会覆盖前一个属性。因此,您只会看到水平居中。
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translateY(-50%); /* This would be overwritten */
transform: translateX(-50%); /* By this.. */
}
解决方案是像这样组合这些值:
transform: translateX(-50%) translateY(-50%);
或者..
transform: translate(-50%, -50%);
Updated Example - 添加了供应商前缀。
关于css - 使用 translateX/Y 垂直和水平居中未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25677464/