position:relative; 相対的な位置を示す
position: relative;
positionの値をrelative に指定すると、positionプロパティでstaticを指定した場合に表示される位置が基準位置となり、ボックスの位置を相対的位置で配置します。実際の位置は、top、right、bottom、left プロパティで指定します。
もっと詳しく position: relative
「position: relative;を指定すると、ボックス要素は相対的な位置で配置されます。
直前にある要素からの位置を基準とし、相対位置を指定するプロパティです。position: absolute;が絶対位置なのに対して、position:
relative;は、直前の要素からの位置決めなので、ボックスを重ねる、画像の位置をずらす、重ねて見せたい時はとても便利です。
こちらの4枚の写真はもともと1行1列に並んでいましたが、position: relative;を使って2番目の写真は下にずらし、4番目の写真はとなりの写真に重なるようにしてみました。
サンプル − 画像の位置をずらす
sample css ↓
.gazo_a{
position: relative;
top: 30px;
left: 0px;
}
.gazo_b {
position: relative;
top: 30px;
left: -20px;
}
html ↓
<html>
<body>
<img src="1.jpg" width="100" height="100"
/>
<img src="2.jpg" class="gazo_a" width="100"
height="100" />
<img src="3.jpg" width="100" height="100"
/>
<img src="4.jpg" class="gazo_b" width="100"
height="100" />
</body>
</html>
サンプル − position-relativeでボックスを配置
position-relativeでボックスを配置すると下記の丸印が座標位置になります。直前の要素からの位置決めなので、sample2では、left: 140px 親要素の左端から右方向へ、140pxずれて、top: 0px; なので、高さは、sample1と同じ位置になります。続けてsample3では、top: 10px; left: 10px; なので、直前の要素sample2より、10px下に下がり、親要素の左から10px右の位置に配置されます。
sample css ↓
.box {/*親ボックス*/
position: absolute;
top: 50px;
left: 150px;
width: 350px;
height: 250px;
border: 1px solid #999;
}
.sample1_box{/*sample1ボックス*/
position: relative;
top:0px;
left:0px;
height:60px;
width: 150px;
background-color: #ccc;
}
.sample2_box{/*sample2ボックス*/
position: relative;
top:0px;
left:140px;
height:60px;
width: 150px;
background-color: #ccccff;
}
.sample3_box{/*sample3ボックス*/
position: relative;
top:10px;
left:10px;
height:60px;
width: 150px;
background-color: #fcf;
}
html ↓
<html>
<body>
<div class="box">
<div class="sample1_box">sample1 box</div>
<div class="sample2_box">sample2 box</div>
<div class="sample3_box">sample3 box</div>
</div>
</body>
</html>
実際の見え方 ↓