2012-05-10 60 views
4

我正在嘗試使文本停留在可調整大小的DIV中。 這裏的例子:如何將文本保存在div中,始終處於中間?

CSS

#rightmenu { 
    position: absolute; 
    z-index: 999999; 
    right: 0; 
    height: 60%; 
    text-align: center; 
} 

HTML

<div id="rightmenu">This text should be center aligned and in the middle of the resizable rightmenu</div> 

我試圖做一個類包含的「上邊距和下邊距」文本上都汽車,但不起作用。

+0

你的意思是你想要的文字垂直居中?感謝W3C的無限智慧,這對於標準CSS來說是不可能的,並且需要多種黑客,解決方法和額外的標記。 –

回答

8

如果你不關心IE7的支持,你可以做這樣的:

HTML:

<div id=wrap> 
    <div id=inside> 
    Content, content, content. 
    </div> 
</div> 

CSS:

#wrap { 
    /* Your styling. */ 
    position: absolute; 
    z-index: 999999; 
    right: 0; 
    height: 60%; 
    text-align: center; 

    /* Solution part I. */ 
    display: table; 
} 

/* Solution part II. */ 
#inside { 
    width: 100%; 
    height: 100%; 
    display: table-cell; 
    vertical-align: middle; 
} 

代碼:http://tinkerbin.com/ETMVplub

如果你還可以使用JavaScript,你可以試試這個jQuery插件:http://centratissimo.musings.it/但是因爲它似乎也不支持IE7,CSS解決方案可能更好。

+0

完美!非常感謝你!這正是我所需要的,並且一如既往地期望IE會有一些問題..大聲笑。謝啦。 – rmz

0

如果你想要的文字在一個div水平居中,「文本對齊:中心;」是你的朋友。如果你想要它垂直居中;將內容包裝在內部div中,然後對該內部div使用'margin:auto'。當然,你必須給內部div一個寬度;否則,水平中心將不起作用。
「VALIGN =‘中間’」也適用於表,如果表是一個選項(否則灰心)

0

檢查這是需要:

<html> 
<head> 
<style type="text/css"> 
div { 
    height: 100px; 
    width: 100px; 
    background: #ccc; 
    text-align: center; 
} 
p { 
    line-height: 100px; 
} 
</style> 
</head> 
<body> 
<div> 
    <p>centered</p> 
</div> 
</body> 
</html> 
1

Flexbox確實在流體中的方式對位元件改變了比賽。定義你的容器元素爲display: flex,然後結合你的內心,你的孩子會用justify-content: center; align-items: center;

.container { 
    position: absolute; 
    top: 0; 
    right: 0; 
    bottom: 0; 
    left: 0; 
    display: flex; 
    justify-content: center; 
    align-items: center; 
} 
.parent { 
    height: 500px; 
    width: 500px; 
    position: relative; 
} 


<div class="parent"> 
    <div class="container"> 
     <p>Hello</p> 
     <p>World</p> 
    </div> 
</div> 

你會發現,「你好」和「世界」都將是.container元素中的垂直和水平居中。

相關問題