我以前从未遇到过这种情况。我在各种地方试过 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 许可协议
您可以使用 flexbox 来使用此解决方案。
改变了什么?
flex-direction: column
to.boxes
to define how the flex items (<p>
element) are placed in the flex container (.boxes
).align-items: center
使弹性项目沿水平轴居中。justify-content: center
使弹性项目(<p>
元素)在垂直轴上居中。