2017-02-18 6 views
0

私はしばらくの間、物事を垂直にセンタリングするために比較的配置された要素を使用してきました。しかし、なぜposition: relative; top: 50%;が要素を垂直方向に中心に置いていないのか理解できませんでした。またはは、少なくともコンテナdiv内の要素の上端の中央に配置されています。 MDNに従ってトップ:50%;実際には相対的に位置づけられた要素上にある

position: 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

関連する問題