6. 定位
6.1 position属性
-
CSS position 属性用于指定一个元素在文档中的定位方式。top,right,bottom 和 left 属性则决定了该元素的最终位置。
-
position属性的常见值如下表所示:
属性值 属性秒数 static 默认值,没有定位 relative 相对定位 absolute 绝对定位 fixed 固定定位
6.2 static属性值
-
元素没有进行定位。此时 top, right, bottom, left 和 z-index 属性无效。
-
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,minimum-scale=1,user-scalable=no" /> <title>没有定位元素</title> <link rel="shortcut icon" href="favicon.svg" type="image/x-icon" /> <style> .app { width: 300px; margin: 0 auto; border: 1px solid #000; padding: 10px; } .box1, .box2, .box3 { padding: 10px; margin-bottom: 10px; border: 1px dashed #000; } .box1 { background-color: #f2bb6f; } .box2 { background-color: #003580; color: #fff; } .box3 { margin-bottom: 0; background-color: #f0f0f0; } </style> </head> <body> <div class="app"> <div class="box1">第一个盒子</div> <div class="box2">第二个盒子</div> <div class="box3">第三个盒子</div> </div> </body> </html>
-
效果图
6.3 relative属性值
-
相对自身原来位置进行偏移
-
偏移设置:top、left、right、bottom
-
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,minimum-scale=1,user-scalable=no" /> <title>relative定位元素</title> <link rel="shortcut icon" href="favicon.svg" type="image/x-icon" /> <style> .app { width: 300px; margin: 100px auto; border: 1px solid #000; padding: 10px; } .box1, .box2, .box3 { padding: 10px; margin-bottom: 10px; border: 1px dashed #000; /* 1. 相对于自己的位置进行定位 2. 没有脱离文档流 3. 自己位置不会被其它元素占用 4. 不会对其它元素产生影响 */ position: relative; } .box1 { background-color: #f2bb6f; top: -20px; left: 20px; } .box2 { background-color: #003580; color: #fff; } .box3 { margin-bottom: 0; background-color: #f0f0f0; right: 20px; bottom: 30px; } </style> </head> <body> <div class="app"> <div class="box1">第一个盒子</div> <div class="box2">第二个盒子</div> <div class="box3">第三个盒子</div> </div> </body> </html>
-
效果图
-
相对定位特点
- 设置相对定位的盒子会相对它原来的位置,通过指定偏移,到达新的位置
- 设置相对定位的盒子仍在标准文档流中,它对父级盒子和相邻的盒子都没有任何影响
- 设置相对定位的盒子原来的位置会被保留下来
6.4 浮动元素设置相对定位
-
设置第二个盒子右浮动,再设置第一、第二盒子相对定位
-
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>float元素的relative定位</title> <link rel="shortcut icon" href="favicon.svg" type="image/x-icon" /> <style> .app { width: 300px; margin: 100px auto; border: 1px solid #000; padding: 10px; } .box1, .box2, .box3 { padding: 10px; margin-bottom: 10px; border: 1px dashed #000; } .box1 { background-color: #f2bb6f; position: relative; right: 20px; bottom: 20px; } .box2 { background-color: #003580; color: #fff; float: right; position: relative; left: 20px; top: -20px; } .box3 { margin-bottom: 0; background-color: #f0f0f0; } </style> </head> <body> <div class="app"> <div class="box1">第一个盒子</div> <div class="box2">第二个盒子</div> <div class="box3">第三个盒子</div> </div> </body>