通過position屬性來設(shè)置元素的相對(duì)定位
position: relative;
當(dāng)元素的position屬性設(shè)置為relative時(shí),則開啟了元素的相對(duì)定位
- 當(dāng)開啟了元素的相對(duì)定位以后,而不設(shè)置偏移量時(shí),元素不會(huì)發(fā)生任何變化
- 相對(duì)定位是相對(duì)于元素在文檔流中原來的位置進(jìn)行定位
- 相對(duì)定位的元素不會(huì)脫離文檔流,位置保留
- 相對(duì)定位會(huì)使元素提升一個(gè)層級(jí),比文檔流高一些,會(huì)蓋住
- 相對(duì)定位不會(huì)改變?cè)氐男再|(zhì),塊還是塊,內(nèi)聯(lián)還是內(nèi)聯(lián)
當(dāng)開啟了元素的定位(position屬性值是一個(gè)非static的值)時(shí),
可以通過left right top bottom四個(gè)屬性來設(shè)置元素的偏移量
left:元素相對(duì)于其定位位置的左側(cè)偏移量
right:元素相對(duì)于其定位位置的右側(cè)偏移量
top:元素相對(duì)于其定位位置的上邊的偏移量
bottom:元素相對(duì)于其定位位置下邊的偏移量
通常偏移量只需要使用兩個(gè)就可以對(duì)一個(gè)元素進(jìn)行定位,
一般選擇水平方向的一個(gè)偏移量和垂直方向的偏移量來為一個(gè)元素進(jìn)行定位
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
.box1{
width: 200px;
height: 200px;
background-color: red;
}
.box2{
width: 200px;
height: 200px;
background-color: yellow;
position: relative;
left: 100px;
top: 200px;
}
.box3{
width: 200px;
height: 200px;
background-color: yellowgreen;
}
.s1{
position: relative;
width: 200px;
height: 200px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<span class="s1">我是一個(gè)span</span>
</body>
</html>
預(yù)覽:

image.png