關於CSS 的position定位問題
對於初學者來說,css的position定位問題是比較常見的。之前搞不清楚postion定位是怎麽回事,排版一直歪歪斜斜的,老是排不好
css的定位一般來說,分為四種:
position:static;
position:relative;
position:absolute;
position:fixed;
其中:
1. static是默認屬性,當不給定position屬性時,系統會自動設置為static屬性;
2.relative是相對屬性,設定方法就是:position:relative; 這個相對屬性,是針對他原來的位置進行相對,不是相對父元素,也不是相對根元素,這點要搞清楚,此處最容易混淆的地方
3.absolute是絕對定位,它的參照為父級元素,且父級元素的position屬性為非 static ;如果父級元素position是static,那就接著向上找,找父級的父級,直到父級元素position 屬性為非static 為止;如果全部父級元素position 屬性都是static ,那它的參照就是body根元素
4.fixed是固定定位,定位也是一個絕對值,不過它的參照不是父級元素,而是可視窗窗口;(通常用在固定位置 的導航,或者返回頂部按鈕)
例如:
1.position:static;不設定時,自動設置position為static;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin:0; padding:0; } .box1{ width:300px; height:200px; background:red; } .box2{ width:200px; height:200px; background:blue; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div> </body> </html>
2. position:relative 設定相對屬性
設置相對屬性後,原來元素所占據的空間不會變化,當給定上、下、左、右相對偏移量後,元素會相對原來的位置進行偏移
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin:0; padding:0; } .box1{ position:relative; left:80px; top:40px; width:300px; height:200px; background:red; } .box2{ width:200px; height:200px; background:blue; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div> </body> </html>
3. position:absolute 設定絕對定位,參照父級元素進行定位
參照根元素body絕對定位
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin:0; padding:0; } .box1{ left:80px; top:40px; width:300px; height:200px; background:red; } .box2{ position:absolute; width:200px; height:200px; background:blue; top:40px; left:80px; } </style> </head> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html>
參照父級div.box1進行絕對定位
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin:0; padding:0; } .box1{ position:relative; left:80px; top:40px; width:300px; height:200px; background:red; } .box2{ position:absolute; width:200px; height:200px; background:blue; top:40px; left:80px; } </style> </head> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html>
4. position:fixed; 設定固定定位;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin:0; padding:0; } .box1{ position:relative; left:180px; top:140px; width:300px; height:200px; background:red; } .box2{ position:fixed; width:200px; height:200px; background:blue; top:40px; left:80px; } </style> </head> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html>
以上就是個人對於css 定位的理解,如需真正掌握,還需要多練習幾次
關於CSS 的position定位問題