【CSS】position: relative;とposition: absolute;子要素にもなる親要素にはどっちをつけるの


画像に画像を重ねて表示させたい時などに、親要素にはposition: relative;、子要素にはposition: absolute;を指定すれば親要素の上で表示させたい場所に配置させることができますよね。

ところが、下のように用意したものを


このようにするにはオレンジの「parent」に
position: relative;とabsoluteのどちらを指定すればいいのか迷ってしましました。

子要素にもなる親要素
まず「parent」は「child」の親要素なので
このように指定しました。
.parent {
position: relative;
}
.child {
position: absolute;
top: 40px;
left: 3px;
}

このようにうまく配置できました。
「parent」を「bg」の左上に配置する
親に「 position: relative;」ということで「parent」の親になる「bg」に「position: relative;」を指定してみます。
.bg {
position: relative;
}
.parent {
position: relative;
top: 10px;
left: 10px;
}
.child {
position: absolute;
top: 40px;
left: 3px;
}

指定前

top:100px;
left:100px;
「bg」には重ならず離れてしましました。
やりたいことと違いますね。
親にもposition: absolute;
今度は「parent」にposition: absolute;を指定します。
.bg {
position: relative;
}
.parent {
position: absolute;
top: 10px;
left:10px;
}
.child {
position: absolute;
top: 40px;
left: 3px;
}

するとこのように配置したい場所に表示することができました。
子要素の「child」も離れずついてきてくれています。
まとめ
祖先要素には「position: relative;」
親要素には「position: absolute;」
子要素には「 position: absolute;」
で配置させることができました。
同じカテゴリの記事一覧へ