1. 程式人生 > >h5--------相對定位,絕對定位

h5--------相對定位,絕對定位

相對定位

效果圖


<!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屬性來設定元素的定位
* -可選值:
* static:預設值,元素沒有開啟定位
* relative:開啟元素的相對定位
* absolute:開啟元素的絕對定位
* fixed:開啟元素的固定定位(也是絕對定位的一種)
*/

/*
* 當元素的position屬性設定為relative時,則開啟了元素的相對定位
* 1.當開啟了元素的相對定位以後,而不設定偏移量時,元素不會發生任何變化
*  2.相對定位是相對於元素在文件流中原來的位置進行定位
* 3.相對定位的元素不會脫離文件流
* 4.相對定位會使元素提升一個層級
* 5.相對定位不會改變元素的性質,塊還是塊,內聯還是內聯
*/
position: relative;


/*
* 當開啟了元素的定位(position屬性值是一個非static的值)時,
* 可以通過left right top bottom四個屬性來設定元素的偏移量
* left:元素相對於其定位位置的左側偏移量
* right:元素相對於其定位位置的右側偏移量
* top:元素相對於其定位位置的上邊的偏移量
* bottom:元素相對於其定位位置下邊的偏移量

* 通常偏移量只需要使用兩個就可以對一個元素進行定位,
* 一般選擇水平方向的一個偏移量和垂直方向的偏移量來為一個元素進行定位
*/

/*left: 100px;
top: 200px;*/

left: 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時,則開啟了元素的絕對定位

* 絕對定位:
* 1.開啟絕對定位,會使元素脫離文件流
* 2.開啟絕對定位以後,如果不設定偏移量,則元素的位置不會發生變化
* 3.絕對定位是相對於離他最近的開啟了定位的祖先元素進行定位的(一般情況,開啟了子元素的絕對定位都會同時開啟父元素的相對定位)
* 如果所有的祖先元素都沒有開啟定位,則會相對於瀏覽器視窗進行定位
* 4.絕對定位會使元素提升一個層級
* 5.絕對定位會改變元素的性質,
* 內聯元素變成塊元素,
* 塊元素的寬度和高度預設都被內容撐開
*/
position: absolute;

/*left: 100px;
top: 100px;*/

}
.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>