垂直居中方法Translate(Y)无法工作——稍微偏离中心。

4

我有一段简单的代码,可以在页面上垂直和水平居中一个文本元素:

 body {
   max-width: 1200px;
   margin: 0 auto;
 }

 .container {
   position: relative;
   transform-style: preserve-3d;
   height: 100vh;
 }

 .center {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translateY(-50%);
 }

这样做将文本置于容器的垂直中心,但在水平方向上略微偏右。我认为使用"left: 50%"应该可以正确地水平居中它,对吗?

2个回答

7

接近正确了,但你还需要添加translateX。幸运的是,有一个简单的缩写方式可以同时实现X和Y变换:

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

由于 left: 50% 的设置使得元素的左侧正好位于50%处,因此它略微偏离中心。通过添加 transformX(-50%) 可以抵消这些额外的空间。请查看下面的代码片段:

.box-container {
  position: relative;
  height: 200px;
}

.center-box {
  position: absolute;
  background: black;
  width: 50px;
  height: 50px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="box-container">
  <div class="center-box"></div>
</div>


3
如果您会使用flexbox,那么我建议您使用它。这将使得以下内容非常简单:

body {
  margin: 0;
}

.container {
  height: 400px; /* Just for the snippet */
  width: 400px; /* Just for the snippet */
  background-color: #f4f4f4; /* Just for the snippet */
  margin: 0 auto; /* Just for the snippet */
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="container">
  <div class="center">
    This is centered
  </div>
</div>

你可以在这里查找有关flexbox浏览器支持的信息:http://caniuse.com/#search=flex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接