在前台進行頁面位置編輯時,時常碰到頁面部分標簽位置錯亂,因此研究了一下通過css進行定位標簽的方法.
定位方式:是指如何確定某個標簽在頁面中的位置.
1.固定定位:始終相對於瀏覽器窗口進行定位
1 <html> 2 <head> 3 <title>定位方式-固定定位</title> 4 <meta charset="utf-8"> 5 <style type="text/css"> 6 body{ 7 height: 2000px; 8 } 9 div{ 10 width: 500px; 11 height: 300px; 12 border:solid 2px red; 13 position: fixed;/*設置定位方式為固定定位*/ 14 bottom:500px 1px ; 15 } 16 p{ 17 float: right; 18 } 19 20 </style> 21 </head> 22 <body> 23 <div>這是一個div盒子</div><br> 24 <p>這個不會動</p> 25 </body> 26 </html>
2.相對定位:用來對標簽的位置進行微調,參照的是標簽原來的位置
1 <html> 2 <head> 3 <title>定位方式-相對定位</title> 4 <meta charset="utf-8"> 5 <style type="text/css"> 6 body{ 7 height: 2000px; 8 } 9 #span2{ 10 position: relative;/*設置定位方式為相對定位*/ 11 top: 20px; 12 left: 14px; 13 } 14 </style> 15 </head> 16 <body> 17 <span id="span1">這是一個</span> 18 <span id="span2">這是一個</span> 19 <span id="span3">這是一個</span> 20 </body> 21 </html>
3.絕對定位:元素的位置相對於最近的已定位祖先元素(relative對象),如果元素沒有已定位的祖先元素,那么它的位置相對於最初的包含塊----body
1 <head> 2 <title>定位方式-絕對定位</title> 3 <meta charset="utf-8"> 4 <style type="text/css"> 5 div{ 6 width: 500px; 7 height: 400px; 8 border: solid 2px red; 9 /*給div設置相對定位,使得div作為section的參照物進行絕對定位*/ 10 position: relative; 11 } 12 section{ 13 width: 50px; 14 height: 40px; 15 background-color: yellow; 16 position: absolute;/*設置定位方式為絕對定位*/ 17 /*讓section始終在div右下角*/ 18 /*讓section相對在div右側距離為0*/ 19 /*讓section相對在div低側距離為0*/ 20 /*絕對定位必須設置參照物,若未設置參照物,則相對於body進行定位*/ 21 right: 0px; 22 bottom: 0px; 23 } 24 25 </style> 26 </head> 27 <body> 28 <div> 29 <section></section> 30 </div> 31 </body>
懂得了這三種通過css進行定位的方式,相信以后前台頁面標簽錯亂的問題就會得到很好地解決.