相對定位
效果圖
<!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: 200px;
}
/*
* 定位:
* - 定位指的就是將指定的元素擺放到頁面的任意位置
* 通過定位可以任意的擺放元素
* - 通過position屬性來設置元素的定位
* -可選值:
* static:默認值,元素沒有開啓定位
* relative:開啓元素的相對定位
* absolute:開啓元素的絕對定位
* fixed:開啓元素的固定定位(也是絕對定位的一種)
*/
/*
* 當元素的position屬性設置爲relative時,則開啓了元素的相對定位
* 1.當開啓了元素的相對定位以後,而不設置偏移量時,元素不會發生任何變化
* 2.相對定位是相對於元素在文檔流中原來的位置進行定位
* 3.相對定位的元素不會脫離文檔流
* 4.相對定位會使元素提升一個層級
* 5.相對定位不會改變元素的性質,塊還是塊,內聯還是內聯
*/
/*
* 當開啓了元素的定位(position屬性值是一個非static的值)時,
* 可以通過left right top bottom四個屬性來設置元素的偏移量
* left:元素相對於其定位位置的左側偏移量
* right:元素相對於其定位位置的右側偏移量
* top:元素相對於其定位位置的上邊的偏移量
* bottom:元素相對於其定位位置下邊的偏移量
*
* 通常偏移量只需要使用兩個就可以對一個元素進行定位,
* 一般選擇水平方向的一個偏移量和垂直方向的偏移量來爲一個元素進行定位
*/
/*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">我是一個span</span>
</body>
</html>
絕對定位
效果圖
<!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: absolute;
/*left: 100px;
top: 100px;*/
}
/*
* 當position屬性值設置爲absolute時,則開啓了元素的絕對定位
*
* 絕對定位:
* 1.開啓絕對定位,會使元素脫離文檔流
* 2.開啓絕對定位以後,如果不設置偏移量,則元素的位置不會發生變化
* 3.絕對定位是相對於離他最近的開啓了定位的祖先元素進行定位的(一般情況,開啓了子元素的絕對定位都會同時開啓父元素的相對定位)
* 如果所有的祖先元素都沒有開啓定位,則會相對於瀏覽器窗口進行定位
* 4.絕對定位會使元素提升一個層級
* 5.絕對定位會改變元素的性質,
* 內聯元素變成塊元素,
* 塊元素的寬度和高度默認都被內容撐開
*/
.box3{
width: 300px;
height: 300px;
background-color: yellowgreen;
}
.box4{
width: 300px;
height: 300px;
background-color: orange;
/*開啓box4的相對定位*/
/*position: relative;*/
}
.s1{
width: 100px;
height: 100px;
background-color: yellow;
/*開啓絕對定位*/
position: absolute;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box5">
<div class="box4">
<div class="box2"></div>
</div>
</div>
<div class="box3"></div>
<span class="s1">我是一個span</span>
</body>
</html>