CSS定位元素有3種方式 :普通流、相對位置、絕對位置。經過設置position屬性來實現。瀏覽器
inherit | 繼承父元素position 屬性的值。spa |
static3d |
默認值。沒有定位,元素出如今正常的流中(忽略 top, bottom, left, right 或者 z-index 聲明)。code |
relativeblog |
生成相對定位的元素,相對於元素自己正常位置進行定位。所以,"left:20" 會向元素的 LEFT 位置添加 20 像素。繼承 |
absoluteci |
生成絕對定位的元素,找到第一個非static的祖先元素進行定位。元素的位置經過 "left", "top", "right" 以及 "bottom" 屬性進行規定。文檔 |
fixedit |
生成絕對定位的元素,相對於瀏覽器窗口進行定位。元素的位置經過 "left", "top", "right" 以及 "bottom" 屬性進行規定。io |
普通流定位是:static,默認定位 相對位置定位是:relative 相對於該元素自己做爲普通流的位置,佔有文檔流的原來位置
絕對位置定位有2種:absolute和fixed,一個是相對本身的第一個非static祖先元素,一個是相對瀏覽器窗口,都不佔有原來的文檔流位置
例子1:static普通流定位,紅色div的top屬性失效
<body> <div style="border: solid 1px #0e0; width: 200px;"><div style="height: 100px; width:100px; background-color:red; top:20px;"></div> <div style="height:100px; width:100px; background-color:green; "></div> <div style="height:100px; width:100px; background-color:blue;"></div> </div> </body>
例子2:relative相對位置,綠色div相對static的位置向右和向下移動了20px,綠色div原來的文檔位置還在。
<body> <div style="border: solid 1px #0e0; width: 200px;"><div style="height: 100px; width:100px; background-color:red; top:20px;"></div> <div style="height:100px; width:100px; background-color:green; position:relative; top:20px; left:20px;"></div> <div style="height:100px; width:100px; background-color:blue;"></div> </div> </body>
例子3.1:absolute絕對位置(不佔有原來的文檔流位置),沒有指定父元素div的position屬性,則綠色div的父級div是static定位,因此不選這個div作參照,選window做爲參照
<body> <div style="border: solid 1px #0e0; width: 200px;"> <div style="height: 100px; width:100px; background-color:red; top:20px;"></div><div style="height:100px; width:100px; background-color:green; position:absolute; top:20px; left:20px; "></div> <div style="height:100px; width:100px; background-color:blue;"></div> </div> </body>
例子3.2:absolute絕對位置,父級div的position是relative,再也不是static,因此選父級div爲參考。
<body> <div style="border: solid 1px #0e0; width: 200px; position:relative;"> <div style="height: 100px; width:100px; background-color:red; top:20px;"></div> <div style="height:100px; width:100px; background-color:green; position:absolute; top:20px; left:20px; "></div><div style="height:100px; width:100px; background-color:blue;"></div> </div> </body>
例子4:fixed絕對位置,相對於窗口window的,不佔文檔流位置。
<body> <div style="border: solid 1px #0e0; width: 200px; position:relative;"> <div style="height: 100px; width:100px; background-color:red; top:20px;"></div> <div style="height:100px; width:100px; background-color:green; position:fixed; bottom:20px; left:20px; "></div> <div style="height:100px; width:100px; background-color:blue;"></div> </div> </body>