1. 程式人生 > >position定位的認識

position定位的認識

代碼示例 block color one utf-8 style add viewport bottom

首先

position有五個取值:static(靜態)、relative、absolute、fixed、sticky

1、static:默認的定位方式,應用該定位的元素在文案流內。此時 top, right, bottom, leftz-index 屬性無效。

2、relative:應用該定位的元素在文檔流內,他會占據原有的位置,從原有的位置進行偏移。

3、absolute:應用該定位的元素會脫離文檔流,他會自動向上級尋找定位的元素,當找到有定位的元素,就會以那個元素來進行相對定位,如果他的父級或祖先級沒有定位的 元素,就以body元素進行絕對定位,此定位會跟著頁面滾動而滾動。

4、fixed:應用該定位的元素會脫離文檔流,此元素相對於屏幕視口的位置來定位,當頁面滾動時,此元素不會隨著頁面滾動而滾動

5、sticky:應用該定位的元素在文檔流內,此元素會在文檔的正常位置,此元素在它父元素的容器內是類似fixed定位,當他與後續的塊級元素粘粘時,他會被頂走

下面是代碼示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"
> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <style> *{ margin: 0; padding: 0; } .box div{ width: 200px; height: 200px; background-color: aquamarine; margin-right
: 30px; display: inline-block; text-align: center; font-size: 30px; line-height: 200px; } .two{ position: relative; left: 20px; top: 20px; } .box .three{ position: absolute; left: 100px; background-color:rgb(194, 173, 176); z-index: 77; opacity: .6; } .box2{ height: 600px; position: relative; } .a{ position: sticky; height: 100px; width: 100px; top: 100px; background-color: rgb(182, 189, 186); margin-bottom: 100px; } .b{ position: sticky; height: 100px; width: 100px; top: 50px; opacity: .8; background-color: rgb(118, 219, 175); } .box3{ height: 1200px; background-color: aquamarine; } </style> <body> <div class="box"> <div class="one">one</div> <div class="two">two</div> <div class="three">three</div> <div class="four">four</div> </div> <div class="box2"> <div class="a">absol</div> <div class="b"></div> </div> <div class="box3"></div> </body> </html>

position定位的認識