CSS相對定位、絕對位置,CSS定位,定位
CSS定位屬性:position。
定位的基本思想:定義元素框相對於其正常位置應該出現的位置,或者相對於父元素、另一個元素或瀏覽器視窗本身的位置。
position屬性值:static、relative、absolute、fixed。
以下所有測試在Firefox40.0下進行。
所用到基本代碼:
1 <style> 2 body{ 3 margin: 30px 0 0 30px; 4 padding: 0; 5 } 6 .div1{ 7 width: 200px; 8 height: 200px; 9 padding: 50px;10 background: red;11 }12 .div2{13 width: 50px;14 height: 50px;15 background-color: blue;16 }17 .div3{18 background-color: pink;19 width: 80px;20 height: 50px;21 }22 .div4{23 background-color: gray;24 width: 80px;25 height: 50px;26 }27 </style>
1 <body>2 <div class="div1"><div class="div2">div2</div>div1</div>3 <div class="div3">div3</div>4 <div class="div4">div4</div>5 </body>
普通定位:static,預設情況。不設定position屬性時,會按照正常的文檔流進行排列。
固定定位:fixed,絕對位置的第二種情況(見下文)。
相對定位:relative,元素框位移某個距離(相對於它原來的位置),它原本的位置空間仍然保留。
1 .div3{2 background-color: pink;3 width: 80px;4 height: 50px;5 position: relative;6 left: 300px;7 }
DIV3向左位移了300px,原來的位置還在(DIV4並沒有貼上去)。
在元素有父元素的情況下,也是一樣的。
1 .div2{2 width: 50px;3 height: 50px;4 background-color: blue;5 position: relative;6 left: 250px;7 }
絕對位置:元素框在正常文檔流中所佔據空間關閉,並相對於其包含框定位。包含框可能是文檔中的另一個元素框或者是視窗本身。元素定位後產生一個塊級框,而不論原來它在正常流中產生何種類型的框。
分兩中情況:
第一種情況:
.div1{ position: relative; width: 200px; height: 200px; padding: 50px; background: red;}.div2{ position: absolute; left: 300px; top: 0; width: 50px; height: 50px; background-color: blue;}
從明顯看到,DIV2向左位移300px,是從內邊距左上方開始的,而不是DIV2原始的位置(如果padding為0,則是從原始的位置)。
設定DIV1的外邊距為30px,DIV2位移left、top都為0。
1 .div1{ 2 position: relative; 3 margin: 30px; 4 width: 200px; 5 height: 200px; 6 padding: 50px; 7 background: red; 8 } 9 .div2{10 position: absolute;11 left: 0;12 top: 0;13 width: 50px;14 height: 50px;15 background-color: blue;16 }
可見,在父元素框有外邊距的情況下,位移也是從內邊距開始的。
第二種情況:
body內邊距增加30px,DIV2向右位移360px。
body{ margin: 30px 0 0 30px; padding: 30px;}.div1{ width: 200px; height: 200px; padding: 50px; background: red;}.div2{ position: absolute; left: 360px; top: 60px; width: 50px; height: 50px; background-color: blue;}
左邊body空白處有外邊距、內邊距各30px,DIV2位移30px+30px+300px=360px,剛好與DIV1對齊。證明位移是從視窗的左上方,而不用管內外邊距!