css中的定位属性为:position
其的属性值为: static、 relative、fixed、absolute、sticky
一、static:静态定位
HTML 元素的默认值,即没有定位,遵循正常的文档流对象。
静态定位的元素不会受到 top, bottom, left, right影响。
<style>
div{
position: static;
height: 100px;
width: 100px;
top: 1000px;
left: 100px;
background-color: #7B2F2F;
}
</style>
![](https://i-blog.csdnimg.cn/blog_migrate/bd5c101bcc70b5c2e57b1377644ecc5a.png)
二、relative:相对定位
相对定位 relative相对于原来的位置不脱离标准文档流。在使用相对定位时,无论是否进行移动,元素仍然占据原来的空间。移动元素会导致它覆盖其它框。(不脱离标准文档流)
<style>
#box1{
position: relative;
height: 100px;
width: 100px;
top: 200px;
left: 100px;
background-color: #7B2F2F;
}
#box2{
height: 100px;
width: 100px;
background-color: #1C036C;
}
</style>
![](https://i-blog.csdnimg.cn/blog_migrate/2a299cb013c9892ec779035b0e39334c.png)
![](https://i-blog.csdnimg.cn/blog_migrate/f6cfee25ad16de44e6bbe67be7bc7e75.png)
三、fixed:固定定位
脱离标准文档流,保留原本的位置。不管你怎么滑动,他都相对于窗口位置不变。
<style>
.divA{
position: fixed;
top: 100px;
left: 100px;
}
</style>
<div class="divA">
<img src="./images/user.png">
</div>
![](https://i-blog.csdnimg.cn/blog_migrate/ec62e70e084d3e54861f25e272d9b846.png)
![](https://i-blog.csdnimg.cn/blog_migrate/3385377c39a8538f0da33d3b1434d765.png)
四、absolute:绝对定位
脱离标准文档流,不保留原本的位置。
<style>
.father {
margin-top: 50px;
margin-left: 50px;
width: 500px;
height: 500px;
background-color: skyblue;
}
.son {
position: absolute;
top: 50px;
left: 50px;
width: 200px;
height: 200px;
background-color: pink;
}
</style>
![](https://i-blog.csdnimg.cn/blog_migrate/dc1d6e4af14c25925006169862e64658.png)
![](https://i-blog.csdnimg.cn/blog_migrate/8e6711758b66a307feb065a90e713e55.png)
五、sticky:粘性定位
sticky可以说是 静态定位static 和 固定定位fixed 的混合体。元素在跨越特定阈值前为相对定位,之后为固定定位。这个特定阈值指的是 top, right, bottom 或 left 之一,换言之,指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
height: 3000px;
}
.nav{
/* 粘性定位 */
position: sticky;
width: 100px;
height: 50px;
background-color: pink;
margin: 10px;
left: 1500px;
}
</style>
</head>
<body>
<div class="nav">我是导航栏</div>
</body>
![](https://i-blog.csdnimg.cn/blog_migrate/d56a7b4ef8d88891be26d0d236d977bb.png)