relative相对定位
relative相对定位,相对于自己原本的位置进行定位,自己原本的位置空间还存在。
<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
* {
margin: 0;
padding: 0;
}
div {
width: 100px;
height: 100px;
}
.one {
background-color: cadetblue;
}
.two {
position: relative;
top: 50px;
left: 50px;
background-color: aquamarine;
}
.three {
background-color: bisque;
}
absolute绝对定位
absolute绝对定位是相对于自己的父元素进行定位的,而自己原本的位置将会被其它元素占领。
<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
* {
margin: 0;
padding: 0;
}
div {
width: 100px;
height: 100px;
}
.one {
background-color: cadetblue;
}
.two {
position: absolute;
top: 50px;
left: 50px;
background-color: aquamarine;
}
.three {
background-color: bisque;
}
fixed固定定位
fixed固定定位与绝对定位相似,都是基于父元素进行定位的,但如果设置了滚动条之后,滚动的时候位置依然固定不变。
<div class="home">
<div class="one">one</div>
<div class="two">two</div>
</div>
.home {
width: 500px;
height: 300px;
overflow: scroll;
}
.one {
position: fixed;
top: 50px;
left: 50px;
background-color: aquamarine;
width: 100px;
height: 100px;
}
.two {
background-color: bisque;
height: 500px;
}
sticky粘性定位
sticky粘性定位的元素是依赖于用户的滚动,在 position:relative 与 position:fixed 定位之间切换。例如顶部固定、顶部固定就是用sticky实现。注意须指定 top
、 right
、 bottom
、 left
四个阈值其中之一,才可使粘性定位生效
<div class="sticky">我是粘性定位!</div>
<div style="padding-bottom: 2000px">
<p>滚动我</p>
<p>来回滚动我</p>
<p>滚动我</p>
<p>来回滚动我</p>
<p>滚动我</p>
<p>来回滚动我</p>
</div>
.sticky {
position: sticky;
top: 0;
padding: 5px;
background-color: #cae8ca;
border: 2px solid #4caf50;
}
static静态定位
静态定位的元素不会受到 top, bottom, left, right影响,定位的元素,无特殊定位,遵循正常的文档流对象。
inherit定位
继承父元素的position的
值