絕對位置 position:absolute,相對定位 position:relative,absoluterelative
《1》
當我們要使用絕對位置的時候,必須要有兩個條件
1》必須給父元素加定位屬性,一般建議使用 position:relative(即:給父元素設為相對定位);
2》給子項目,加絕對位置position:absolute(給子項目設定為絕對位置); 同時加方向屬性(top ,left,rigth,bottom)
絕對位置是以父元素為基準點,進行定位(如果他沒有父元素,或者它的父元素沒有設定position:relative屬性)它就會以<body>為基準點進行定位。絕對位置會脫離文檔流(即:他浮動起來了,不再佔據原來的位置了)
絕對位置
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> body { margin:0px; padding:0px; } div { width: 100px; height: 100px; } #main { width:500px; height:500px; border:1px solid red; margin:0px 250px; } #a { background-color: red; } #b { background-color: green; top:100px; left:100px } #c { background-color: blue; height:150px; width:150px; } </style></head><body> <div id="main"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div></body></html>
《2 給子項目添加絕對位置,不給父元素添加相對定位,那麼子項目進行絕對位置就是以body為基準進行定位的》
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> body { margin:0px; padding:0px; } div { width: 100px; height: 100px; } #main { width:500px; height:500px; border:1px solid red; margin:0px 250px; /*position:relative;*/ /*不給父元素設定相對定位,那麼子項目就會以body為基準進行定位*/ } #a { background-color: red; } #b { background-color: green; top: 100px; left: 100px ; position:absolute; /*給B設定絕對位置*/ } #c { background-color: blue; height:150px; width:150px; } </style></head><body> <div id="main"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div></body></html>
《3最終,給父元素添加相對定位,給子項目添加絕對位置,那麼子項目進行絕對位置就是以父元素為基準進行定位的》
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> body { margin:0px; padding:0px; } div { width: 100px; height: 100px; } #main { width:500px; height:500px; border:1px solid red; margin:0px 250px; position:relative; /*給父元素設定相對定位,那麼子項目進行絕對位置的時候就會以父元素為基準進行定位*/ } #a { background-color: red; } #b { background-color: green; top: 100px; left: 100px ; position:absolute; /*給B設定絕對位置*/ } #c { background-color: blue; height:150px; width:150px; } </style></head><body> <div id="main"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div></body></html>