positionとは
position は CSS のプロパティで、文書内で要素がどのように配置されるかを設定します。 top, right, bottom, left の各プロパティが、配置された要素の最終的な位置を決めます。
引用:MDN Web Docs
top, right, bottom, leftで要素の位置を決めたい時に設定が必要
static
top, right, bottom, leftによる位置設定が適用されなくなる
<div id="red" class="box"></div>
<div id="blue" class="box"></div>
<div id="green" class="box"></div>
#red {
background: red;
position: static;
top: 40px;
}
#blue {
background: blue;
top: 40px;
}
#green {
background: green;
}
#red, #blueはstaticが設定されるためtop: 40pxは適用されない
※#blueのようにposition自体を設定していない場合はstaticと同じ挙動になる
relative
周りの要素を基準にして位置設定を行う
#red {
background: red;
}
#blue {
background: blue;
position: relative;
left: 40px;
}
#green {
background: green;
}
上記の場合、#redの要素を基準に40px空けて#blueの要素をに配置する
absolute
親要素を基準にして要素を配置する。
周りの要素に位置が被る場合は重ねて前面に表示される。
#red {
background: red;
}
#blue {
background: blue;
position: absolute;
left: 40px;
}
#green {
background: green;
}
上記の場合、親要素(画面左端)を基準に40px空けて配置される。
位置が被っている#redは背面に表示
fixed
常に画面端を基準に要素が配置される
画面サイズを変更した場合も設定した間隔を維持して配置され続ける。
#red {
background: red;
}
#blue {
background: blue;
}
#green {
background: green;
position: fixed;
right: 40px;
}
#greenの要素は画面右を基準に40px空けて配置される。画面サイズを変更しても位置は変わらない。
fixed 補足
親要素にtransform, perspective, filterが設定されている場合、親要素を基準に配置される
<div class="container">
<div id="red" class="box"></div>
<div id="blue" class="box"></div>
<div id="green" class="box"></div>
</div>
.container {
background: gray;
width: 400px;
transform: translate(100px); /* X方向へ100px移動 */
}
#red {
background: red;
}
#blue {
background: blue;
}
#green {
background: green;
position: fixed;
right: 40px;
}
上記の場合、親要素にtransform: translateが設定されているため、配置の基準は画面右ではなく親要素(灰色の部分)になる。
sticky
スクロールなどで要素が指定の位置(top, right, bottom, leftの設定値)を超えると固定で表示される。
.box {
width: 100px;
height: 100px;
position: sticky;
top: 10px;
margin-bottom: 50px;
}
#red {
background: red;
}
#blue {
background: blue;
}
#green {
background: green;
}
上記の場合、赤青緑ブロックの上部が10px以下になると画面上に固定されるようになる。
参考サイト
↧