css--定位
阿新 • • 發佈:2020-08-01
CSS定位方式:相對 絕對 固定
一、相對定位
position: relative; 預設值為staticleft: 10px; 距左
top: 20px; 距上 所以效果為:向右下移動
相對定位 相對於自己原來的位置
特點 1 不脫標 2 原來位置保留,老家留坑 3可以提升層級 使用 1 相對自己進行位置微調 2 配合絕對定位使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width, initial-scale=1.0"> <title>Document</title> <style> /*position: relative; left: 10px; 距左 top: 20px; 距上 所以效果為:向右下移動 相對定位 相對於自己原來的位置 1 不脫標 2 原來位置保留,老家留坑 3可以提升層級 使用 1 相對自己進行位置微調 2 配合絕對定位使用 */ .box1{ width: 200px; height: 200px; background-color:red; /* 預設值 */ position: static; position: relative; left: 10px; top: 20px; } .box2{ width: 100px; height: 100px; background-color: blueviolet; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div> </body> </html>
二、絕對定位
position:absolute;參考點: 1 假如該絕對定位元素 沒有定位(相對or絕對or固定)的祖先元素
則以body為參考點
2 假如有定位的祖先,則以最近的定位祖先元素為參考點 特性 :1 脫標 2 假如不設定寬度,則由內容撐開
使用:子絕父相
兒子採用絕對定位,父親採用相對定位,此時,兒子可以在父親範圍內任意定位
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> /* 絕對定位 position:absolute; 參考點: 1 假如該絕對定位元素 沒有定位(相對or絕對or固定)的祖先元素 則以body為參考點 2 假如有定位的祖先,則以最近的定位祖先元素為參考點 特性 :1 脫標 2 假如不設定寬度,則由內容撐開 使用:子絕父相 兒子採用絕對定位,父親採用相對定位,此時,兒子可以在父親範圍內任意定位 */ .box3-fa{ width: 300px; height: 300px; border: 4px dashed purple; position: relative; left: 40px; top: 30px; } .box3{ width: 200px; height: 200px; background-color: cyan; position: absolute; left: 20px; top: 30px; } </style> </head> <body> <div class="box-gradfa"> <div class="box3-fa"> <div class="box3"></div> </div> </div> </body> </html>絕對定位
三、固定定位
position: fixed;
參考點:始終以瀏覽器視窗左上角為參考點
特點 1 脫標 2 層級高於標準流元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> /* 固定定位 position: fixed; 參考點:始終以瀏覽器視窗左上角為參考點 特點 1 脫標 2 層級高於標準流元素 */ .box3-fa{ width: 300px; height: 300px; border: 4px dashed purple; position: relative; left: 40px; top: 30px; } .box3-fa >.box3{ width: 200px; height: 200px; background-color: cyan; position: fixed; left: 20px; top: 30px; } </style> </head> <body> <div class="box-gradfa"> <div class="box3-fa"> <div class="box3"></div> </div> </div> </body> </html>