2015-09-10 18 views
1

我想在水平方向和垂直居中一個div使用利用絕對位置和左的方法:-50%等垂直居中的div失敗,使用「位置:絕對」定心方法

然而,將不能成爲垂直居中,只能水平。

結果不是垂直居中: enter image description here

爲什麼?

http://jsfiddle.net/6cLwwrxc/

HTML

<div class="background"> 
    1<br>2<br>3<br>4<br>5<br>6<br> 
    <div class="overlay"> 
    <div>foobar</div> 
    </div> 
</div> 

CSS

.background 
{ 
    border: 1px solid black; 
    position: relative; 
} 

.overlay 
{ 
    position: absolute; 
    top: 50%; 
    left: 50%; 
} 

.overlay > div 
{ 
    background: #888; 
    color: #fff; 
    position: relative; 
    top: -50%; 
    left: -50%; 
    padding: 10px; 
} 

如果我使用的margin-top:的-50%代替top: -50%.overlay > div,在foobar的DIV移動太遠向上:

enter image description here

顯然身高百分比與背景div有關。

+0

http://jsfiddle.net/6cLwwrxc/2/ – SpiRT

回答

1

計算沒有考慮元素的高度。如果您從定位時的高度減去一半的高度,則可以將其居中。

http://codepen.io/anon/pen/jbbVpP

.overlay > div { 
    background: #888; 
    color: #fff; 
    position: relative; 
    top: -50%; 
    left: -50%; 
    padding: 10px; 
    margin-top: -20px; 
} 

CSS技巧有a good way of doing thistranslate

.parent { 
    position: relative; 
} 
.child { 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    transform: translate(-50%, -50%); 
} 
+0

如果我使用'transform'我得到的滾動條,好像該元素未被轉換。有一個問題,我不能總是使用'overflow:hidden'來防止這種情況發生。 –