定位
-
1.相对定位:占位置
-
作用:1.父相子绝;
- 2.微调元素
比如:两个元素底边没有对齐,可设置以下
input{ font-size: 30px; } span { position: relative; top: 2px; } </style> </head> <body> <span>hahah</span> <input type="text">
然后浏览器右击检查
调好后,不要忘记将代码中的top一同修改,不然修改不了
-
2.绝对定位:不占位置(即脱离标准文档流)
.box1 { height: 100px; width: 100px; background-color: red; /*position: absolute;*/ } .box2 { height: 100px; width: 100px; background-color: green; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div>
对box1设置position: absolute;之后;
box1脱离了标准文档流,不占位置,相当于box1飘起来了,此时浏览器第一个盒子是box2,box2顶到了box1的位置,被box2覆盖在上边;
绝对定位盒子居中:
position:absolute;
left: 50%;
margin-left: -width/2;
-
.wrap { width: 200px; height:100px; background-color: yellow; margin: 0 auto /*标准流的盒子居中*/ } </style> </head> <body> <div class="wrap"></div>
结果:
-
对其设置position:absolute后,不在居中,
在对其设置left: 50%; margin-left: -50px;就可居中。
-
标准流的盒子居中
-
margin:0 auto;
3.固定定位 脱离标准流 不占位置
-
1.比如固定导航栏等,京东
-
.header{ width: 100%; height:70px; background-color: green; position: fixed; } </style> </head> <body> <div class="header"></div>
- 添加 top: 0;left: 0;可以直接顶到最上边
添加z-index:1000;绿色导航栏覆盖在上边
但是红色和黄色盒子依旧在绿色下边,需要将两个盒子往下移,设置body:padding-top: 100px 或者:body:margin-top:100px 即可