CSS属性之定位
定位(position)作为CSS中使用频率较高的几大类属性之一,在页面布局,排版,页面功能化方面起着不可或缺的作用,其作为CSS基础中的一个较难点,成为了很多前端入门者学习的困扰,接下来我们来聊聊CSS中定位的那些事。
顾名思义,浮动强调悬浮,定位强调位置,定位的关键点在于其位置以及参照物的选取。
定位有以下几种常用属性:relative(相对),absolute(绝对),fixed(固定),sticky(粘性),当然还有其默认属性:static(默认值)。
情况分析
首先我们想象自己在一个空房间里,你自己就是一个子元素,因为你站在某一块地砖上,所以我们把地板上的一块地板砖当作是你的父元素,现在我们把房间失重定义为一种状态并叫做——脱离文档流,我们把四面的墙壁起名分别是top,bottom,left,right。
情况一
当我们给自己添加属性:position:absolute;之后,我们会处于一种失重的状态,此时我们会离开我们所依赖的地面而悬浮到空中,此时我们把四面的墙壁作为我们的参照物(放在浏览器中就是我们的第一窗口),此时left,right,top,bottom就作为我们衡量我们现在位置的尺度,如果我们没有定义该属性,我们就会悬浮在浏览器的左上角。但此刻如果我们在该状态的基础上再给我们的地板添加属性position:relative;或position:fixed;或position:absolute;
这时这块地板砖的引力会变大,会让我们吸附到上面,此时我们的参照物就是这块地板砖,同样的此时left,right,top,bottom作为定义我们位置的标准。
<style>
.box1{
width: 300px;
height: 300px;
background-color: tomato;
}
.box2{
width: 100px;
height: 100px;
background-color: gold;
position: absolute;
right: 50px;
}
</style>
<div class="box1">
<div class="box2">
我是我自己
</div>
</div>
<style>
.box1{
width: 300px;
height: 300px;
background-color: tomato;
position: relative;
}
.box2{
width: 100px;
height: 100px;
background-color: gold;
position: absolute;
right: 50px;
}
</style>
<div class="box1">
<div class="box2">
我是我自己
</div>
</div>
情况二
当我们给自己添加属性:position:relative;之后,我们不会处于失重状态,即不会脱离文档流而存在,但此时我们以自己为参照物,若使用了top,bottom,right,left控制距离我们可以考虑为相对于自己进行平移,同时不再以地面作为我们的参考,我们可以去到另外的地板转上面。
<style>
.box1{
width: 300px;
height: 300px;
background-color: tomato;
}
.box2{
width: 100px;
height: 100px;
background-color: gold;
position: relative;
top: 400px;
}
.box3{
width: 300px;
height: 300px;
background-color: violet;
}
</style>
<div class="box1">
我是地板
<div class="box2">
我是我自己
</div>
</div>
<div class="box3">
我是地板2
</div>
情况三
当我们给自己添加属性:position:fixed;之后,我们会处于失重状态,离开我们所在的父元素,即脱离文档流而存在,此时left,right,top,bottom作为我们衡量我们现在位置的尺度,但是特殊的一点是我们的位置不会随着浏览器滚动条的滚动而变化,相比于absolute来说,这种位置更为强硬,absolute只是相对于浏览器的第一屏,在滚动条存在的情况下,拖动滚动条会是元素位置移动。
<style>
.box1{
width: 300px;
height: 1000px;
background-color: tomato;
}
.box2{
width: 100px;
height: 100px;
background-color: gold;
position: fixed;
right: 50px;
}
</style>
<div class="box1">
我是地板
<div class="box2">
我是我自己
</div>
</div>
<style>
.box1{
width: 300px;
height: 1000px;
background-color: tomato;
}
.box2{
width: 100px;
height: 100px;
background-color: gold;
position: absolute;
right: 50px;
}
</style>
<div class="box1">
我是地板
<div class="box2">
我是我自己
</div>
</div>
情况四
当我们给自己添加属性:position:sticky;这种状态是相对和固定定位状态的综合,在某些状态下处于相对定位的状态,即占据自己的位置且不脱离我们所在的地板砖,当超出一定范围之后,我们会被吸附在房间的top壁上,对于浏览器来说就是窗口顶部。
<style>
.box1{
width: 300px;
height: 1000px;
background-color: tomato;
}
.box2{
width: 100px;
height: 100px;
background-color: gold;
position: sticky;
top: 0;
}
</style>
<div class="box1">
我是地板
<div class="box2">
我是我自己
</div>
</div>