2014-09-19 32 views
0

我一直被这个令人讨厌的问题所困扰......我无法将文本居中放在div中。DIV中的中心文字

我设法让文本在BEGIN的中心,但我希望整个文本都居中。

这是我的例子 - 任何提示和技巧非常赞赏。

#box { 
 
    position: absolute; 
 
    top: 100px; 
 
    left: 50%; 
 
    height: 100px; 
 
    width: 450px; 
 
    text-align: center; 
 
    margin: 0px 0px 0px -225px; 
 
    border: 2px solid black; 
 
} 
 
#TEXT { 
 
    position: absolute; 
 
    top: 30px; 
 
    left: 50% 
 
}
<div id="box"> 
 
    <p id="TEXT">This text is not centered</p> 
 
</div>

我的例子:http://jsfiddle.net/y97myrap/

+0

不要编辑问题,你可以“接受”一个答案,向人们展示哪一个人为你解决问题。 – Flexo 2014-09-20 06:02:19

回答

1

使用text-align:center;删除position: absolute;,如果你给width到CON这将工作cerned div ....

div100%宽,然后text-align:center;将在中心推动一切

#box { 
 
    position: absolute; 
 
    top: 100px; 
 
    left: 50%; 
 
    height: 100px; 
 
    width: 450px; 
 
    text-align: center; 
 
    margin: 0px 0px 0px -225px; 
 
    border: 2px solid black; 
 
} 
 
#TEXT { 
 
    position: absolute; 
 
    top: 30px; 
 
    width:100%; 
 
    text-align:center; 
 
    <!-- left: 50% --> 
 
}
<div id="box"> 
 
    <p id="TEXT">This text is not centered</p> 
 
</div>

0

Fot的使用绝对位置为中心的元素,常见的方法设置:

position:absolute; 
left:50%; 
margin left:{Minus half of the width of the element you want to center} 

所以,我的建议R您情况如下:

http://jsfiddle.net/y97myrap/1/

使用外部div容器,然后将文本对齐到一个, 如果你想中心的高度为好,如果父高度是固定的,你可以只使用一个线高度上的文字相同的高度容器,就像这样:

http://jsfiddle.net/y97myrap/5/

0
#TEXT { 
    position: relative; 
    top:20% 
} 

Try it

2
 <div style="text-align:center;"> 
     data is here 
    </div> 

在HTML5

+0

** 1。**这不是HTML5 ** 2 ** OP有'绝对'元素,所以这不起作用** 3。**一般不建议使用内联CSS! :) – NoobEditor 2014-09-19 07:08:42

+0

kkkk我明白了...... – Dhawan 2014-09-19 07:10:47

+0

btw ...你的DP ...是GOHAN还是GOTENKS? – NoobEditor 2014-09-19 07:11:49

0

它是运用图像高度的一半的负边距的一件简单的事,和宽度的一半的负左边距。

代码:

#box { 
position: fixed; 
top: 50%; 
left: 50%; 
margin-top: -50px; 
margin-left: -100px; 
} 

这会使对象的位置固定,可以调整DIV的位置,根据自己的需要。

0

您可以使用display: table tecnique。在子元素添加在容器tabletable-cell

#box { 
 
    position: absolute; 
 
    top: 100px; 
 
    left: 50%; 
 
    height: 100px; 
 
    width: 450px; 
 
    text-align: center; 
 
    margin: 0px 0px 0px -225px; 
 
    border: 2px solid black; 
 
    display: table;/*Add display table*/ 
 
} 
 
#TEXT { 
 
    display: table-cell;/*Add display table cell*/ 
 
    vertical-align: middle;/*add vertical-align middle*/ 
 
}
<div id="box"> 
 
    <p id="TEXT">This text is not centered</p> 
 
</div>

+0

**小心:** IE8 +支持! – NoobEditor 2014-09-19 07:10:54

+0

我希望人们不要再支持IE8了:) – 2014-09-19 07:14:33

0

在骗取钱财的问题是,你有立场:绝对的;和50%的左边...我猜你试图以这种方式居中,但问题是文本块将在50%之后开始。删除位置,给它text-align:center ;.

而要对齐垂直考虑使用表格单元格

0

取出的位置是:绝对的,只是添加自动margings您#TEXT:

#TEXT { 
    top: 30px; 
    left: 50% 
    margin-left: auto; 
    margin-right:auto; 
} 
0

此代码解决了这个问题:

#TEXT { 
position: relative; 
display: block; 
text-align: center; 
width: 100%; 
top: 30px; 
}