Text-align: center 和 align-items: center 不水平工作

新手上路,请多包涵

我以前从未遇到过这种情况。我在各种地方试过 text-align: center 但它们都不起作用。它们垂直工作,但不水平工作。我试图让它在每个盒子的水平和垂直方向上工作。

这是我的代码:

 .boxes {
  height:100%;
}
.box {
  width: 33%;
  height: 20%;
  display: -webkit-flex;
}
.box p {
  display: flex;
  align-items: center;
}
.box1 {
  background: magenta;
}
.box2 {
  background: cyan;
}
.box3 {
  background: yellow;
}
.box4 {
  background: orange;
}
.box5 {
  background: purple;
}
* {
  margin:0;
  padding:0;
}
html, body {
  height: 100%;
}
 <!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="tabletest.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
    <div class="boxes">
      <div class="box box1"><p>Box 1</p></div>
      <div class="box box2"><p>Box 2</p></div>
      <div class="box box3"><p>Box 3</p></div>
      <div class="box box4"><p>Box 4</p></div>
      <div class="box box5"><p>Box 5</p></div>
    </div>
  </body>
</html>

我也试图坚持百分比以获得响应式设计。

编辑:这似乎与另一篇文章重复,但我的问题是如何让文本直接居中对齐(垂直和水平),同时保持框的顺序。

原文由 m_cht 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 415
2 个回答

您可以使用 flexbox 来使用此解决方案。

改变了什么?

 * {
  margin: 0;
  padding: 0;
}
html, body {
  height: 100%;
}

.boxes {
  height: 100%;
}
.box {
  align-items: center;
  display: flex;
  flex-direction: column;
  height: 20%;
  justify-content: center;
  width: 33%;
}
.box1 {
  background: magenta;
}
.box2 {
  background: cyan;
}
.box3 {
  background: yellow;
}
.box4 {
  background: orange;
}
.box5 {
  background: purple;
}
 <div class="boxes">
  <div class="box box1"><p>Box 1</p></div>
  <div class="box box2"><p>Box 2</p></div>
  <div class="box box3"><p>Box 3</p></div>
  <div class="box box4"><p>Box 4</p></div>
  <div class="box box5"><p>Box 5</p></div>
</div>

原文由 Sebastian Brosch 发布,翻译遵循 CC BY-SA 4.0 许可协议

只需添加

justify-content: center;

到你的 box 班级。

这就是您需要做的全部。看 这里

原文由 DeveloperDahak 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题