css樣式中的position到底有幾種屬性值?常用的就三種relative,absolute,fixed,但是作爲一名專業的人員別人問你position有那些屬性值,只說三種是不行的,應該把他所有存在的屬性值都列出來,有以下7種:
屬性值 | 屬性值使用描述 |
---|---|
static | 默認值,元素出現在文檔流正常的地方 |
absolute | 絕對定位當前元素,相對於第一個非static定位以外的第一個父元素進行定位,以left,right,top,bottom進行定位 |
relative | 相對定位當前元素,相對於其正常出現的位置進行定位,如left:20px,就是相對原始位置向左移動20像素 |
fixed | 生成相對視窗定位的元素,將當前元素相對於瀏覽器窗口進行定位。元素的位置通過 “left,top,right,bottom” 屬性進行確定位置 |
sticky | 粘性定位,在當前定位的元素的父元素可見時,父元素區域內固定位置,ps:下面會展開詳細解讀一下 |
inherit | 從父元素繼承 position屬性值 |
initial | 設置該屬性爲默認值 |
sticky:粘性定位,乍一看不好明白,舉個例子就懂了:
<div>
<div class="wrap"></div>
<hr/>
<div class="wrap">
<div id="stickyBox">
我是sticky box
</div>
<div id="fixedBox">
我是fixed box
</div>
</div>
</div>
css
<style>
.wrap{
width: 100%;
height: 301.25rem;
background-color: antiquewhite;
}
#stickyBox{
position: sticky;
top: 50px;
width: 200px;
height: 60px;
background-color: aqua;
margin: auto;
}
#fixedBox{
position: fixed;
right: 100px;
bottom: 100px;
width: 60px;
height: 60px;
background-color: aqua;
}
</style>
可以看到當sticky定位的元素在當前父元素滾動範圍內會像fixed定位一樣,超出其父元素後則會回到初始位置。
從上向下,從第一個容器向下滾動的時候:
進入sticky父元素前:
sticky對象的父元素滾動區域內:
一直滾動底部:
從下向下上,從第二個容器向上滾動的時候:
超出sticky元素的父元素滾動邊界了,所以sticky回到初始位置
okay…就這樣