我希望我的<p>元素位于容器<div>的中心,就像完全居中一样--顶部、底部、左侧和右侧的页边距平均地分割空格。
我怎样才能做到这一点呢?
div {
width: 300px;
height: 100px;
}
p {
position: absolute;
top: auto;
}<div>
<p>I want this paragraph to be at the center, but it's not.</p>
</div>
发布于 2013-02-28 04:12:45
你不需要绝对定位使用
p {
text-align: center;
line-height: 100px;
}随心所欲地调整。
如果文本超出宽度并超过一行,则为
在这种情况下,您可以做的调整是在您的规则中包含显示属性,如下所示;
(我添加了一个背景,以便更好地查看示例)
div
{
width:300px;
height:100px;
display: table;
background:#ccddcc;
}
p {
text-align:center;
vertical-align: middle;
display: table-cell;
}在此JBin中使用它

发布于 2013-02-28 04:19:53
将左/右居中,然后将text-align: center应用于div,将margin: auto应用于p。
对于垂直定位,你应该确保你理解不同的方法,这是一个常见的问题:Vertical alignment of elements in a div
发布于 2017-09-16 01:04:07
♣您应该执行以下步骤:
子元素的位置应该是“positioned(for position:relative;)
>E126>子元素和母元素 =>
子元素和母元素的“:auto”(要成为中间页边距)。
♣♣这里简单地概括了这5个步骤:
.mother_Element {
position : relative;
height : 20%;
width : 5%;
text-align : center
}
.child_Element {
height : 1.2 em;
width : 5%;
margin : auto;
position : absolute;
top:0;
bottom:0;
left:0;
right:0;
}https://stackoverflow.com/questions/15121343
复制相似问题