‘position: relative;’を付与すると、’top, right, bottom, left’を使って本来の位置から相対的に自由な配置が可能になりますが、実際には、relativeを親要素にして、absoluteを子要素にする方法が便利なpositionの使い方です。
‘position: absolute;’を付与すると、ブロック要素でもインライン要素でもなく、特別な浮いた要素になります。親要素の左上端を基準にして、’top, right, bottom, left’プロパティを使って、位置を決めます。
コード 例
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>position: relative と absolute で自由な配置をする</title>
<style>
h1 {
color: #333;
border-bottom: 2px solid #ccc;
padding-bottom: 10px;
margin-bottom: 30px;
}
/* 親要素 position: relative; */
.parent-box {
width: 400px;
height: 250px;
background-color: #e0ffe0; /* 薄い緑色 */
border: 3px dashed #7bc97b; /* 点線ボーダー */
padding: 20px;
margin: 50px auto; /* この要素の横位置を真ん中にする */
position: relative; /* 子要素のabsoluteの基準点となる */
font-size: 1.2em;
color: #4a4a4a;
}
/* 子要素 position: absolute; */
.child-box {
background-color: #ffcc99; /* オレンジ色 */
border: 2px solid #e69138;
padding: 10px;
color: #333;
font-size: 0.9em;
position: absolute; /* relativeが掛かっている要素を親にして、つまり基準にして位置を指定できるようになる */
width: 120px; /* 幅を設定 */
height: 60px; /* 高さを設定 */
}
/* 子要素の具体的な配置 */
.child-top-left {
top: 0;
left: 0;
}
.child-top-right {
top: 0;
right: 0;
}
.child-bottom-left {
bottom: 0;
left: 0;
}
.child-bottom-right {
bottom: 0;
right: 0;
}
.child-center {
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 中央配置になる */
background-color: #aaddff; /* 青色 */
border-color: #6699ee;
}
</style>
</head>
<body>
<h1>position: relativeとabsoluteの配置例</h1>
<div class="parent-box">
<div class="child-box child-top-left">左上</div>
<div class="child-box child-top-right">右上</div>
<div class="child-box child-bottom-left">左下</div>
<div class="child-box child-bottom-right">右下</div>
<div class="child-box child-center">中央</div>
</div>
</body>
</html>
プレビュー

親要素の’position: relative’がなければ、absoluteは’body’を基準に配置されます。