如何居中 里面的元素 container?

问题描述 投票:32回答:6

我希望我的<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>
html css text centering
6个回答
49
投票

你不需要绝对定位使用

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玩它


9
投票

为了左/右对中,然后将text-align: center应用于divmargin: autop

对于垂直定位,您应该确保了解这样做的不同方法,这是一个常见问题:Vertical alignment of elements in a div


2
投票

♣你应该做这些步骤:

  1. 应该定位母元素(对于EXP,你可以给它位置:相对;)
  2. 子元素应该定位为“绝对”,值应该设置为:top:0; buttom:0; right:0; left:0; (垂直中间)
  3. 对于子元素,你应该设置“margin:auto”(垂直中间)
  4. 孩子和母亲元素应具有“高度”和“宽度”值
  5. 对于母元素=>文本对齐:中心(中间水平)

♣♣这里只是这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;
    }

0
投票

居中和中等内容?

这样做:

<table style="width:100%">
    <tr>
        <td valign="middle" align="center">Table once ruled centering</td>
    </tr>
</table>

fiddled it here

哈,让我猜..你想要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;
}

jsfiddle.net/9Mk64/


0
投票

在p元素上,添加3个样式规则。

.myCenteredPElement{
    margin-left:  auto;
    margin-right: auto;
    text-align: center;
}

-2
投票

你只需要将text-align: center添加到你的<div>

在您的情况下,还删除您添加到<p>的两种样式。

看看这里的演示:http://jsfiddle.net/76uGE/3/

祝好运

© www.soinside.com 2019 - 2024. All rights reserved.