css定位机制
- 普通流
- 定位
- 相对定位:absolute
- 绝对定位:relative
- 固定定位:fixed
- 浮动
普通流
- 简介: 默认是普通流,普通流中元素框的位置由元素在HTML中的位置决定。块级元素从上到下依次排列,框之间的垂直距离由框的垂直margin计算得到;行内元素在一行中水平布置
定位
扩展:使用了position/浮动之后,top、left的设置才有效果
相对定位
- 简介:相对————指的是相对于普通流的时候的位置,可以相对于普通流时候的位置进行上下左右的移动
- 注意:使用相对定位的元素不管它是否进行移动,元素仍要占据它原来的位置。移动元素会导致它覆盖其他的框。
<!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>Document</title>
<style>
.myDiv1{
background-color: red;
width: 200px;
height: 200px;
}
.myDiv2{
position: relative;
background-color: blue;
width: 200px;
height: 200px;
top: 100px;
left: 100px;
}
.myDiv3{
background-color: burlywood;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="myDiv1">你看我</div>
<div class="myDiv2">你看我</div>
<div class="myDiv3">你看我</div>
</body>
</html>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/52e601dee794f286997b70da176b3a50.png)
绝对定位
- 简介:相对于最近的父类元素,如果没有————那么就是相对于body标签,绝对定位是相对于父亲来进行上下左右的移动
- 注意:绝对定位的框脱离普通流,所以它可以覆盖页面上的其他元素,可以通过设置Z-Iindex属性来控制这些框的堆放次序
<!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>Document</title>
<style>
.fatherDiv{
position: relative;
width: 200px;
height: 200px;
background-color: brown
}
.sonDiv{
position: absolute;
top: 100px;
left: 100px;
width: 200px;
height: 200px;
background-color: blue
}
body{
background-color: blanchedalmond
}
</style>
</head>
<body>
<div class="fatherDiv">
<div class="sonDiv">
</div>
</div>
</body>
</html>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6b36a4e738014c17f2eaa4c67e25ac59.png)
- 说明:从图中可以看到其实是相对于父元素的(0,0)位置,而且是脱标的——就是相当于不存在了。。。不会再占用位置而是在别人之上(谁在上面是可以设置的Z-Iindex属性)
固定定位
- 说明:固定于浏览器上,不会随着屏幕的移动而移动——比如说屏幕有下拉,但是就算下拉了,仍在那个位置不会改变。
<!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>Document</title>
<style>
.fixedDiv{
position: fixed;
width: 200px;
height: 200px;
background-color: black
}
body{
background-color: blanchedalmond;
height: 3000px;
}
</style>
</head>
<body>
<div class="fixedDiv"></div>
</body>
</html>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0748ff1d54d9fed4615f511a29f995be.png)
浮动
- 说明:浮动的框可以在左右移动,直到它的外边框边缘碰到包含框或另一个浮动框的边缘。浮动的框脱离普通流——相当于不再占有位置。