定位全解(绝对,相对,固定,粘性定位)
一. 绝对定位(position: absolute)
绝对定位是元素在移动的时候,相对于其父亲来说的(拼爹型),若无父元素,按其祖先元素,如其父元素或祖先元素无定位,则以浏览器为主
元素设置绝对定位后,不再占有原来的位置,其他的元素会涌上来,而且设置绝对定位会压住下面的标准流
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
position: absolute;
top: 10px;
left: 10px;
width: 100px;
height: 100px;
background-color: pink;
}
.box2 {
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
从运行结果来看,绝对定位的元素确实不再占有原来的位置,因为黄色的盒子从下面的位置涌上来了,而且浮动的元素压住了下面的黄色的盒子(标准流)
二. 相对定位(position: relative)
相对定位是元素在移动的时候相对于它原来的位置(自恋型)
原来在标准流的位置会继续占有,其他的元素不会涌上来,后面的元素不会影响原来的位置
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
position: relative;
top: 10px;
left: 10px;
width: 100px;
height: 100px;
background-color: pink;
}
.box2 {
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
由上面的运行结果可以看出原来的位置还在,而且下面的黄色的元素没有涌上来
三. 固定定位(position: fixed)
以浏览器的可视窗口为参照点移动元素
原来在标准流的位置会继续占有,后面的盒子不会影响原来的位置
四. 粘性定位(了解)
以浏览器的可视窗口为参照点移动元素
原来在标准流的位置会继续占有,后面的盒子不会影响原来的位置,其中有一个边偏移才有效果,含义是:当元素的某个位置移动某个距离之后就会固定不动
<style>
body {
height: 3000px;
}
.nav {
position: sticky;
top: 0;
/* 当元素距顶部像素为0时就固定 */
width: 800px;
height: 50px;
background-color: chartreuse;
margin: 100px auto;
}
</style>
<body>
<div class="nav">我是导航栏</div>
</body>