難易度:★★☆☆☆
四方にpaddingを設定した場合
今回は、私の苦手な疑似要素を用いて、親要素にpaddingがあり、
子要素がposition: absolute;配置である場合、
配置の基準位置はpaddingの外側になるか、内側になるか試してみます。
position: absolute;は、親要素がposition:relative;だった場合、
marginを除いた親要素の左上が、top=0,left=0となります。
HTML
<span>wrapper h = 300px</span>
<div class="wrapper">
<div class="inner"><span>inner h = 240px</span></div>
</div>
CSS
.wrapper{
width: 100%;
height: 300px;
background-color: aquamarine;
padding: 30px;
}
.inner{
height: 100%;
background-color: aqua;
text-align: center;
}
inner部分はheight: 100%;を指定していますが、
親要素の上padding30px,下padding30pxを自動計算し、高さ240pxに固定されます。
wrapperの内部に余計な文字などが入ると、要素からはみ出してしまうので、
注意してください。
HTML
<span>wrapper h = 300px</span>
<div class="wrapper"><span>余計な文字</span>
<div class="inner"><span>inner h = 240px(飽くまで!!)</span></div>
</div>
疑似要素を入れてみる…
wrapper h = 300pxbeforeとafterはそれぞれ最初と最後の子要素である事を示しており、
wrapper領域に入る(重なる)順番は、before要素→inner領域→after要素となります。
HTML
<span>wrapper h = 300px</span>
<div class="wrapper has-child">
<div class="inner"><span>inner h = 240px</span></div>
</div>
CSS
.wrapper.has-child{
width: 100%;
height: 300px;
background-color: aquamarine;
padding: 30px;
/* positionプロパティを追加 */
position: relative;
}
.inner{
height: 100%;
background-color: aqua;
text-align: center;
}
.wrapper.has-child::before{
position: absolute;
content: "before";
background-color: steelblue;
width: 75px;
height: 75px;
top: auto;
left: auto;
}
.wrapper.has-child::after{
position: absolute;
content: "after";
background-color: red;
color: #fff;
width: 75px;
height: 75px;
bottom: 0;
right: 0;
}
inner領域のpositionはstaticであり、位置も重なりも指定出来ない状態ですが、
今回は位置を見易くする為のものであり、深く考える必要はありません。
before要素はデフォルト状態と同じtop: auto;,left: auto;を指定していますが、
autoの状態では親要素のpaddingや兄弟要素に影響される(絶対ではない)と言えます。
一方、after要素で示したように、具体的にbottom: 0;,right: 0;または
top: 0;,left: 0;を指定した場合、margin部分にはみ出さず、
paddingを無視して右下の端(左上の端)にピタッとくっつきます。
レイアウトについて、paddingとpositionプロパティ、疑似要素の関係について、
しっかり理解を深めましょう。