我希望我的<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>
你不需要绝对定位使用
p {
text-align: center;
line-height: 100px;
}
并随意调整......
如果文本超出宽度并且超过一行
在这种情况下,您可以执行的调整是在规则中包含display属性,如下所示;
(我添加了一个背景,以便更好地查看示例)
div
{
width:300px;
height:100px;
display: table;
background:#ccddcc;
}
p {
text-align:center;
vertical-align: middle;
display: table-cell;
}
在这个JBin玩它
为了左/右对中,然后将text-align: center
应用于div
和margin: auto
到p
。
对于垂直定位,您应该确保了解这样做的不同方法,这是一个常见问题:Vertical alignment of elements in a div
♣你应该做这些步骤:
♣♣这里只是这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;
}
居中和中等内容?
这样做:
<table style="width:100%">
<tr>
<td valign="middle" align="center">Table once ruled centering</td>
</tr>
</table>
哈,让我猜..你想要DIV ..
只需让你的第一个外部DIV表现得像一个表格单元格,然后用垂直对齐方式设置它:中间;
<div>
<p>I want this paragraph to be at the center, but I can't.</p>
</div>
div {
width:500px;
height:100px;
background-color:aqua;
text-align:center;
/* there it is */
display:table-cell;
vertical-align:middle;
}
在p元素上,添加3个样式规则。
.myCenteredPElement{
margin-left: auto;
margin-right: auto;
text-align: center;
}