CSS Position(定位)
在CSS中,Position 屬性經(jīng)常會用到,主要是絕對定位和相對定位,簡單的使用都沒有問題,尤其嵌套起來,就會有些混亂。
Position?屬性:規(guī)定元素的定位類型。即元素脫離文檔流的布局,在頁面的任意位置顯示。
position 屬性值:
absolute:生成絕對定位的元素,相對于 static 定位以外的第一個父元素進(jìn)行定位。元素的位置通過 "left", "top", "right" 以及 "bottom" 屬性進(jìn)行規(guī)定。
relative:生成相對定位的元素,相對于其正常位置進(jìn)行定位。因此,"left:20" 會向元素的 LEFT 位置添加 20 像素。
fixed:生成絕對定位的元素,相對于瀏覽器窗口進(jìn)行定位。
static:默認(rèn)值。沒有定位,元素出現(xiàn)在正常的流中(忽略 top, bottom, left, right 或者 z-index 聲明)。元素的位置通過 "left", "top", "right" 以及 "bottom" 屬性進(jìn)行規(guī) ? ? ? ? ? ? ? ?定。
inherit:規(guī)定應(yīng)該從父元素繼承 position 屬性的值。
我們最常用的的就是 absolute 和 relative 兩種方式。
position 輔助屬性:
①left?: 表示向元素的左邊插入多少像素,使元素向右移動多少像素。
②right?:表示向元素的右邊插入多少像素,使元素向左移動多少像素。
③top?:表示向元素的上方插入多少像素,使元素向下移動多少像素。
④bottom?:表示向元素的下方插入多少像素,使元素向上移動多少像素。
上面屬性的值可以為負(fù),單位:px 。
Absolute 絕對定位
絕對定位;脫離文檔流的布局,遺留下來的空間由后面的元素填充。定位的起始位置為最近的父元素(postion不為static),否則為Body文檔本身。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>實(shí)例</title> <style type="text/css"> html body { margin: 0px; padding: 0px; } #parent { width: 200px; height: 200px; border: solid 5px black; padding: 0px; position: relative; background-color: green; top: 15px; left: 15px; } #sub1 { width: 100px; height: 100px; background-color: blue; position: absolute; top: 15px; left: 15px; } #sub2 { width: 100px; height: 100px; background-color: red; } </style> </head> <body> <div id="parent"> <div id="sub1"> </div> <div id="sub2"> </div> </div> </body> </html>
注意:我們發(fā)現(xiàn),由于我們對Sub1進(jìn)行了絕對定位,Sub1的位置發(fā)生了偏移,而同級Div Sub2,則占據(jù)了Sub1的位置,并且Sub1遮擋了Sub2.
Relative 相對定位
相對定位;不脫離文檔流的布局,只改變自身的位置,在文檔流原先的位置遺留空白區(qū)域。定位的起始位置為此元素原先在文檔流的位置。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>實(shí)例</title> <style type="text/css"> html body { margin: 0px; padding: 0px; } #parent { width: 200px; height: 200px; border: solid 5px black; padding: 0px; position: relative; background-color: green; top: 15px; left: 15px; } #sub1 { width: 100px; height: 100px; background-color: blue; position: relative; top: 15px; left: 15px; } #sub2 { width: 100px; height: 100px; background-color: red; } </style> </head> <body> <div id="parent"> <div id="sub1"> </div> <div id="sub2"> </div> </div> </body> </html>
?注意:我們會發(fā)現(xiàn)Sub1進(jìn)行了偏移,并不影響Sub2的位置,同時遮蓋住了Sub2,切記偏移并不是相對于 Div Parent的,而是相對于Sub1 原有的位置。
Fixed 定位
固定定位;類似于absolute,但不隨著滾動條的移動而改變位置。
<meta charset="utf-8"> <title>實(shí)例</title> <style type="text/css"> html body { margin: 0px; padding: 0px; } #parent { width: 200px; height: 200px; border: solid 5px black; padding: 0px; position: relative; background-color: green; top: 15px; left: 15px; } #sub1 { width: 100px; height: 100px; background-color: blue; position: absolute; top: 15px; left: 15px; } #sub2 { width: 100px; height: 100px; background-color: red; position: fixed; top: 5px; left: 5px; } </style> </head> <body> <div id="parent"> <div id="sub1"> </div> <div id="sub2"> </div> </div> </body> </html>
注意:?會發(fā)現(xiàn)Sub2 始終以body 進(jìn)行定位。