2017-02-18 26 views
0

我一直在使用相對定位的元素將事物垂直居中一段時間​​。不過,我從來沒有明白,爲什麼position: relative; top: 50%;不會垂直居中元素,至少居中它的容器div中元素的上邊緣。top:50%;實際上是做相對定位的元素?

根據MDNposition: relative

勾畫出的所有元素,就好像元件未定位,並且然後調節元件的位置,而不改變佈局

top關鍵字:

指定元素移動到正常位置以下的數量。

而關於top關鍵字%值:

是對包含塊的高度

所以的百分比與top: 50%的值的相對定位的元件應該被移動50%包含塊的高度向下,對嗎?這是否意味着該元素的頂部邊緣恰好位於包含元素的中間?

考慮這個片斷:

.container { 
 
    overflow: hidden; 
 
    width: 90%; 
 
    height: 90%; 
 
    margin: 0 auto; 
 
    background-color: #eee; 
 
} 
 
.child { 
 
    width: 40%; 
 
    height: 40%; 
 
    margin: 0 auto; 
 
    background-color: #444; 
 
    border-top: 5px solid #f00; 
 
} 
 
.top-50-percent { 
 
    position: relative; 
 
    top: 50%; 
 
} 
 

 
.contract-and-expand { 
 
    animation-name: contract-and-expand; 
 
    animation-duration: 5s; 
 
    animation-iteration-count: infinite; 
 
    animation-timing-function: ease-in-out; 
 
} 
 
@keyframes contract-and-expand { 
 
    50% { 
 
    height: 0%; 
 
    } 
 
}
<html> 
 
    <head> 
 
    <style> 
 
     /* Just initial/basic CSS rules here to make this look better */ 
 
     
 
     @import url("https://necolas.github.io/normalize.css/latest/normalize.css"); 
 

 
     * { 
 
     box-sizing: border-box; 
 
     margin: 0; 
 
     } 
 
     html, body { 
 
     height: 100%; 
 
     } 
 
     body { 
 
     color: #aaa; 
 
     } 
 
     .center-vertically { 
 
     position: relative; 
 
     top: 50%; 
 
     transform: translateY(-50%); 
 
     } 
 
     p { 
 
     position: absolute; /* Remove paragraphs from flow so they don't interfere */ 
 
     } 
 
    </style> 
 
    </head> 
 
    <body> 
 
    <div class="container center-vertically contract-and-expand"> 
 
     <p>Container Wrapper</p> <!-- Paragraphs are removed from the flow --> 
 
     
 
     <div class="child top-50-percent"> 
 
     </div> 
 
     
 
    </div> 
 
    </body> 
 
</html>

從它看起來像頂部邊緣爲中心的片段。這總是正確的嗎?有一個類似的小提琴:https://jsfiddle.net/9kyjt8ze/5/當視口的高度被拉起時,子元素的頂部邊框不再看起來居中。

+0

你懶得看你剛纔的問題嗎? – zer00ne

+0

這個問題導致了這一點...現在它有道理。 –

回答

0

我用Inkscape和2(黃色)垂直塊測量了相同的確切大小。這是一種錯覺。上邊緣從來沒有真正偏離那個小提琴的中心。此外,我所有的假設都顯示正確:top:50%在相對定位的元素上移動該元素的頂部邊框下降50%的容器的高度。這並不是完美垂直居中的原因是上邊緣是在相對定位元素上使用top: 50%時的支點。

enter image description here

相關問題