我知道了 codepen ,虽然它工作得很好,但我不明白为什么它不能将文本居中放置在包含框的中间。以下是我的代码,它垂直居中,现在我也想水平居中。
.container-box p{
position:absolute;
margin:auto;
height:40px;
background:grey;
color:white;
padding:10px;
box-sizing:border-box;
top: 0; left: 0; bottom: 0; right: 0;
display:table;
vertical-align:center;
}
最佳答案
您需要为 margin: auto
(居中)提供一个 width
属性。
.container-box p {
position:absolute;
width: 25%; //add this
margin:auto;
...
}
另一个主要问题是 p
与容器 (.container-box
) 而不是图像居中对齐。 确保图像覆盖整个容器。你可以这样做
.container-box img {
width: 100%;
}
现在看起来文本位于图像的中心,但实际上文本位于容器的中心并且您将图像扩展到整个容器。
关于html - 水平居中绝对元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44563059/