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是相对于浏览器窗口定位但不随窗口的滚动而移动。