本节来讲述 css 中的定位属性(position)。该属性用于控制元素在网页中的位置,通过该属性,我们可以较为精准地进行页面的布局。
position 属性的五个值分别为:
position: static;
position: relative;
position: absolute;
position: fixed;
position: sticky;
1.static
static表示静态定位,是position属性的默认值,无需特意设置。元素一般会按照顺序依次显示,不受top,right,left,bottom 属性的影响。
div {
width: 100px;
height: 100px;
border: 1px solid blue;
}
2.relative
relative表示相对定位。相对定位的元素未脱离文档流,元素相对于默认位置发生偏移,发⽣偏移时可能覆盖其他元素。可与top,right,left,bottom一起使用。
div {
position: relative;
height: 100px;
width: 100px;
top: 50px;
left: 50px;
background-color: blue;
}
3.absolute
absolute表示绝对定位。绝对定位元素一般是相对于最近的非static祖先元素定位(子绝父相)。绝对定位的元素则脱离了文档流,绝对定位元素不占据空间,可能会造成元素重叠的情况。绝对定位可以与top,right,left,bottom一起使用。
<div id="father">
<div id="son">Lorem ipsum dolor sit</div>
</div>
#father {
position: relative;
width: 300px;
height: 200px;
margin: auto;
border: 1px solid red;
}
#son {
position: absolute;
top: 0px;
left: 0px;
border: 1px solid black;
}
4.fixed
fixed表示固定定位。元素的位置相对于浏览器窗口,固定定位脱离了文档流,可以与其它的元素发生重叠。当滚动页面时,元素依旧会固定保持在窗口的相同位置中。可以用于设置悬浮在页面两边或者固定在页面中央的广告等。
<div class="content"></div>
.content {
width: 100px;
height: 100px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: red;
}
5.sticky
sticky表示粘性定位。css3 新增属性值,粘性定位,相当于 relative 和 fixed 的混合。最初会被当作是 relative,相对原来位置进⾏偏移;⼀旦超过⼀定的阈值,会被当成 fixed 定位,相对于视⼝定位。
<div>
<dl>
<dt>A</dt>
<dd>Ab</dd>
<dd>Ac</dd>
<dd>Ad</dd>
<dd>Ae</dd>
<dd>Af</dd>
</dl>
<dl>
<dt>B</dt>
<dd>Ba</dd>
<dd>Bb</dd>
</dl>
<dl>
<dt>C</dt>
<dd>Ca</dd>
<dd>Cb</dd>
<dd>Cc</dd>
<dd>Cd</dd>
</dl>
</div>
dt {
background: blue;
color: white;
padding: 2px 0 0 12px;
position: sticky;
top: -1px;
}
默认情况下:
滑动滚动条后:
再次滑动,B会固定在顶部:
在前端开发的过程中,掌握定位是非常重要的,定位会影响元素在页面中的位置。但是,也不能够滥用定位,否则会使得代码的可维护性变差。