我以前从未遇到过这种情况。我在各种地方尝试了 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>
我也在尝试坚持使用百分比来进行响应式设计。
编辑:这似乎与另一篇文章重复,但我的问题是如何让文本直接居中对齐(垂直和水平),同时保持框的顺序。
最佳答案
您可以通过 flexbox 使用此解决方案。
改变了什么?
- 已添加
flex-direction: column
至.boxes
定义 flex 元素(<p>
元素)如何放置在 flex 容器(.boxes
)中。 - 已添加
align-items: center
使 flex 元素沿水平轴居中。 - 已添加
justify-content: center
使 flex 元素(<p>
元素)在垂直轴上居中。
* {
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>
关于html - 文本对齐 : center and align-items: center not working horizontally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41438699/