起因
寫項目的時候忽然遇到一個問題,子元素絕對定位position: absolute,父元素(box)設置 overflow:scroll超出部分滾動。
結果定位的元素(child-1)仍然會隨著滾動條滾動,按照原先的理解,父元素內部滾動是不會影響固定定位的元素的。
<div class="box">
<div class="child-1"></div>
<div class="child-2"></div>
</div>
<style>
.box {
height: 300px;
background-color: red;
padding-top: 200px;
position: relative;
overflow: scroll;
}
.child-1 {
position: absolute;
top: 0;
height: 100px;
width: 100%;
background-color: green;
z-index: 999;
}
.child-2 {
height: 400px;
background-color: deepskyblue;
}
</style>
結果就是出現橫向滾動條時,child-1元素會跟隨滾動條滾動。
解決方法
出現這樣的問題就是因為父元素設置了position: relative,父元素相對定位會導致,滾動條在滾動的同時,將父元素的位置也移動了,而child-1定位于父元素,所以會跟隨父元素一起滾動。
所以我們解決方法就是在 child-2外層再套一層用于滾動的div。
<div class="box">
<div class="child-1"></div>
<div class="scroll">
<div class="child-2"></div>
</div>
</div>
<style>
.box {
height: 300px;
background-color: red;
position: relative;
overflow: scroll;
}
.child-1 {
position: absolute;
top: 0;
height: 100px;
width: 100%;
background-color: green;
z-index: 999;
}
.scroll {
height: 100%;
overflow: scroll;
padding-top: 200px;
}
.child-2 {
height: 400px;
background-color: deepskyblue;
}
</style>
補充position 屬性小知識點
這個屬性定義建立元素布局所用的定位機制。任何元素都可以定位,不過絕對或固定元素會生成一個塊級框,而不論該元素本身是什么類型。相對定位元素會相對于它在正常流中的默認位置偏移。
| 值 | 描述 |
|---|---|
| absolute | 生成絕對定位的元素,相對于 static 定位以外的第一個父元素進行定位。元素的位置通過 “left”, “top”, “right” 以及 “bottom” 屬性進行規定。 |
| fixed | 生成絕對定位的元素,相對于瀏覽器窗口進行定位。元素的位置通過 “left”, “top”, “right” 以及 “bottom” 屬性進行規定。 |
| relative | 生成相對定位的元素,相對于其正常位置進行定位。因此,“left:20” 會向元素的 LEFT 位置添加 20 像素。 |
| static | 默認值。沒有定位,元素出現在正常的流中(忽略 top, bottom, left, right 或者 z-index 聲明)。 |
| inherit | 規定應該從父元素繼承 position 屬性的值。 |
「喜歡這篇文章,您的關注和贊賞是給作者最好的鼓勵」
關注作者
【版權聲明】本文為墨天輪用戶原創內容,轉載時必須標注文章的來源(墨天輪),文章鏈接,文章作者等基本信息,否則作者和墨天輪有權追究責任。如果您發現墨天輪中有涉嫌抄襲或者侵權的內容,歡迎發送郵件至:contact@modb.pro進行舉報,并提供相關證據,一經查實,墨天輪將立刻刪除相關內容。




