2014-09-19 41 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; 
}