文本对齐:居中和对齐项目:中心不能水平工作

m_c*_*cht 14 html css flexbox responsive-design

以前从未有过这种情况.我尝试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%; 
}
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)

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

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

Seb*_*sch 17

您可以使用以下解决方案,使用flexbox:

.boxes {
  height:100%;
}
.box {
  width:33%;
  height:20%;  
  display:flex;
  flex-direction:column;
  align-items:center;
  justify-content:center;
}
.box1 {
  background: magenta; 
}
.box2 { 
  background: cyan;
}
.box3 {
  background: yellow;
}
.box4 {
  background: orange;
}
.box5 { 
  background: purple;
}
* { 
  margin:0;
  padding:0;
}
html, body {
  height: 100%; 
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 如果您解释为什么所提供的代码解决了OP的问题,那将会很有帮助. (12认同)

小智 9

只需添加

justify-content: center;
Run Code Online (Sandbox Code Playgroud)

到你的box班级。

这就是你需要做的。见这里