css定位
position:
- static默认值,待在文档流里
- relative相对定位,升起来,但不脱离文档流
- absolute绝对定位,定位基准是祖先的元素
- fixed固定定位
- sticky 粘滞定位
1、position:absolute绝对定位
使用场景:脱离原来的位置,另起一层,比如关闭对话框的关闭按钮鼠标提示。
.demo2 {
background: black;
width: 50px;
height: 50px;
<!--基准第一个有定位的元素-->
position: relative;
z-index: -1;
}
.close {
position: absolute;
/* 某些浏览器上不写top/right会位置错乱 */
top: 0;
right: 0;
padding: 0 8px;
background: blue;
color: white;
}
** 注意:很多小白认为absolute是相对于relative定位的 某些浏览器上如果不写top/left会位置错乱 **
2、position:fixed 相对视口定位
使用场景:回到顶部按钮 侧边栏广告
<style>
.container {
border: 1px solid red;
height: 300px;
position: relative;
padding: 20px;
}
.fixed {
border: 1px solid green;
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
font-size: 100px;
}
.fixed {
position: fixed;
left: 10px;
bottom: 10px;
background: green;
}
/* 如果所在的元素,有特殊的属性,就不是视口定位 */
.container {
transform: scale(0.9);
}
/* 如果所在的元素,有特殊的属性,就不是视口定位 */
.container {
transform: scale(0.9);
}
</style>
<body>
<div class="container">
<div class="fixed">▲</div>
</div>
</body>
注意:手机尽量不要用这个属性,会出现很多bug。
3、sticky 粘滞定位
使用场景:可以滚动的导航栏
注意:兼容性比较差,建议少使用。