一、css定位
CSS 定位属性允许对元素进行定位改变其在页面的位置。
CSS 有三种基本的定位机制:普通流、浮动和绝对定位。
普通流中的元素的位置由元素在 HTML 中的位置决定。
二、相对定位
相对盒子自己原来的位置进行调整,称为相对定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 相对定位
相对自身定位
通常配合绝对定位使用
*/
。box{
position: relative;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
三、绝对定位
绝对定位:盒子可以在浏览器中以坐标进行位置精准描述,拥有自己的绝对位置
堆叠顺序 z-index属性:
决定盒子的层级顺序,值为数字,没有单位,数值大的将覆盖数字小的部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 绝对定位
1.相对浏览器窗口定位
2.父级有定位属性时,相对父级盒子定位
3.逐级往上找,相对碰到的第一个有定位属性的父级盒子定位,
如果没有,就相对浏览器定位
*/
/* 子绝父相
为了让绝对定位有定位点,一般会给他的父级盒子加相对定位
*/
.div1{
position: relative;
top: 0;
left: 0;
}
/*
z-index
设置堆叠顺序
1.默认是z-index: 1
2.数字越大越靠前显示
3.数字越小比如负数越靠后显示
*/
.div2{
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="div1">
<div class="div2"></div>
</div>
</body>
</html>
四、固定定位
固定定位:相对浏览器窗口定位,不随页面滚动改变位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1{
height: 100000px;
}
.box2{
/* 固定定位
相对浏览器窗口定位,不随页面滚动改变位置
*/
position: fixed;
right: 40px;
bottom: 40px;
width: 60px;
height: 300px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>
五、粘性定位
粘性定位:1.偏移量同相对定位
2.页面滚动时,滚动到顶部,直接吸顶
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box2{
/*
粘性定位
偏移量同相对定位
页面滚动时,滚动到顶部,直接吸顶
*/
position: sticky;
top: 100px;
left: 0;
}
.box6{
width: 10px;
height: 100000px;
}
</style>
</head>
<body>
<div class="div1">11</div>
<div class="div2">22</div>
<div class="div3">33</div>
<div class="div4">44</div>
<div class="div5">55</div>
<div class="div6">66</div>
</body>
</html>