私はしばらくの間、物事を垂直にセンタリングするために比較的配置された要素を使用してきました。しかし、なぜ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/ビューポートの高さが引き上げられると、子要素の上の境界線はもはや中央に見えなくなります。
以前の質問を確認しましたか? – zer00ne
その質問はこれにつながった...それは一種の意味が今ではある。 –