2011-11-16 26 views

回答

4

使用display:tabledisplay:table-cell,這在所有的現代瀏覽器上運行(IE 8+):

.post { 
    width: 200px; 
    height: 200px; 
    background: rgba(0,0,0,0.8); 
    display:table; 
} 

.post h2 { 
    text-align: center; 
    width: 100%; 
    height: 100%; 
    display:table-cell; 
    vertical-align: middle; 
} 

.post h2 a { 
    color: #f7f7f7; 
    font-size: 2.2em; 
    font-weight: normal; 
    font-style: italic; 
    width: 100%; 
} 
+0

+1是的,這是一個很好的解決方案。只要你沒有使用IE 7或更老的人,我想。這裏有一篇關於它的好文章:http://www.jakpsatweb.cz/css/css-vertical-center-solution.html – ksindi

1

[增訂]

你也可以做這樣的:jsFiddle

.post { 
    width: 400px; 
    height: 200px; 
    background: rgba(0,0,0,0.8); 
    position:relative;  
} 

.post h2 { 
    position:absolute; 
    top:50%; 
    width:100%; 
    text-align:center; 

} 

.post h2 a { 
    line-height:100%; 
    color: #f7f7f7; 
    font-size: 2.2em; 
    margin-top:-20px; 
    display: block; 
} 
+0

嗯,這似乎只適用於200像素高度的情況。 – ksindi

+0

是的,你是對的...現在我固定,但以不同的方式:-) –

+0

Ooops,...好吧,忘了我的帖子,上面有一個類似的答案 –

1

給你的鏈接一個比文本更大的行高,並在中間垂直對齊。然後,絕對定位它的父的專區內是在top: 50%和利潤率最高減一半鏈接的行高:

jsFiddle

.post { 
    position: relative; 
} 
.post h2 { 
    text-align: center; 
    width: 100%; 
    position: absolute; 
    top: 50%; 
    margin-top: -150px; 
} 
.post h2 a { 
    vertical-align: middle; 
    line-height: 300px; 
    white-space: nowrap; 
} 

它甚至在IE7。

+0

+1似乎適用於所有情況。 – ksindi

+0

實際上「無論任何大小」都無效。 – Wex

+0

@wex - 它不適用於什麼尺寸? – gilly3

2

我想實現它以不同的方式,(只是爲了好玩),而這一次是工作壓力太大: jsFiddle

的想法是用50%的高度的:before塊元素。

html, body{ 
height:100%; 
} 

.post { 
    width: 400px; 
    height: 300px; 
    background: rgba(0,0,0,0.8); 
} 

.post h2:before{ 
    content:""; 
    display:block; 
    height:50%; 
} 

.post h2 { 
    text-align:center; 
    height:100%; 
} 

.post h2 a { 
    color: #f7f7f7; 
    font-size: 2.2em; 
    margin-top:-20px; 
    display: block; 
} 

希望它可以幫助:-)

+0

調整「.post h2 a」字體大小的靈活性並不大。 – Wex

0

如果你不介意的話添加額外的HTML類,你簡單的方法是使用垂直對齊:中間。

http://jsfiddle.net/Wexcode/HtNJM/

<div class="post"> 
    <span></span><h2><a href="#">Hello!</a></h2> 
</div> 

CSS:

* { margin: 0; padding: 0; } 

.post { 
    background: rgba(0,0,0,0.8); 
    width: 200px; 
    height: 200px; } 

.post span { 
    height: 100%; 
    vertical-align: middle; 
    display: inline-block; } 

.post h2 { 
    position: relative; 
    text-align: center; 
    width: 100%; 
    vertical-align: middle; 
    display: inline-block; } 

.post h2 a { 
    color: #f7f7f7; 
    font-size: 2.2em; 
    font-weight: normal; 
    font-style: italic; 
    display: block; }