3.4 固定定位(重要)
注意:固定定位也不占有原来的位置
固定到版心右侧:
版心指的是主内容区
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>固定定位小技巧-固定到版心右侧</title> <style> .w { width: 800px; height: 1400px; background-color: pink; margin: 0 auto; } .fixed { position: fixed; /* 1. 走浏览器宽度的一半 */ left: 50%; /* 2. 利用margin 走版心盒子宽度的一半距离 */ margin-left: 405px; width: 50px; height: 150px; background-color: skyblue; } </style> </head> <body> <div class="fixed"></div> <div class="w">版心盒子 800像素</div> </body> </html>
定位的总结:
3.5 定位叠放次序
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>定位的堆叠顺序</title> <style> .box { position: absolute; top: 0; left: 0; width: 200px; height: 200px; } .xiongda { background-color: red; z-index: 1; } .xionger { background-color: green; left: 50px; top: 50px; z-index: 2; } .qiangge { background-color:blue; left: 100px; top: 100px; } </style> </head> <body> <div class="box xiongda">熊大</div> <div class="box xionger">熊二</div> <div class="box qiangge">光头强</div> </body> </html>
3.6 绝对定位的盒子的居中算法
注意:绝对定位的盒子不能使用margin来实现水平居中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>绝对定位水平垂直居中</title> <style> .box { position: absolute; /* 1. left 走 50% 父容器宽度的一半 */ left: 50%; /* 2. margin 负值 往左边走 自己盒子宽度的一半 */ margin-left: -100px; top: 50%; margin-top: -100px; width: 200px; height: 200px; background-color: pink; /* margin: auto; */ } </style> </head> <body> <div class="box"></div> </body> </html>