relative 與 fixed、absolute兩者的區別:
實驗代碼:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <link rel="stylesheet" href="./class2.css"> 8 <title>css學習</title> 9 </head> 10 <body> 11 <div class="box" id="one">One</div> 12 <div class="box" id="two">Two</div> 13 <div class="box" id="three">Three</div> 14 <div class="box" id="four">Four</div> 15 </body> 16 </html>
1 .box { 2 display: inline-block; 3 width: 100px; 4 height: 100px; 5 background: red; 6 color: white; 7 } 8 9 #two { 10 position:relative; 11 top: 20px; 12 left: 20px; 13 background: blue; 14 }
以 box-two 為實驗對象,當position 屬性為relative時:
當 position 屬性為 fixed 或 absolute 時:
由上述可見,relative屬性是相對於元素本身所處位置而進行定位的,而fixed和absolute元素是相對於瀏覽器窗口而定位的。
fixed 與 absolute 屬性的區別:
1 .box { 2 display: inline-block; 3 width: 100px; 4 height: 1000px; 5 background: red; 6 color: white; 7 }
將box的長度變為1000px,使瀏覽器窗口可以滾動,實驗結果表明:
當position 屬性為 fixed時,box-two 隨瀏覽器窗口向下滾動而移動
當position 屬性為absolute時,不隨瀏覽器窗口滾動而移動
所以,fixed屬性是相對於瀏覽器窗口定位且隨窗口的滾動而移動,而absolute是相對於瀏覽器窗口定位但不隨窗口的滾動而移動。