2013-04-26 102 views
8

我想有一個固定位置的div與溢出-y:滾動,這意味着我希望div留在原地,而其餘的內容正常滾動。 而我無法弄清楚什麼是錯的,有人能幫忙嗎?在此先感謝...固定位置div內pos:相對&溢出-y:滾動

.foo { 
    position:relative; 
    display:block; 
    width:100%; 
    height:300px; 
    overflow-y:scroll; 
} 
.bar { 
    position:fixed; 
    top:0; 
    right:0; 
} 

這裏是HTML

<div class="foo"> 
    <div class="bar"><div><!-- end of div that should be fixed --> 
    <div class="someOther">...</div> 
    <div class="someOther">...</div> 
    <div class="someOther">...</div> 
    <div class="someOther">...</div> 
</div><!-- end of container --> 
+1

固定元素的位置相對於整個頁面而不是它的父元素。 – 2013-04-26 16:28:36

回答

2

的固定元素的位置是相對於您正在查看整個文檔,而不是任何父元素。如果你想要的工作,你需要這樣的事:

CSS

.foo { 
    height : 300px; 
    position : relative; 
    width : 100%; 
} 
.bar { 
    border-bottom : 1px solid #000; 
    height : 50px; 
} 
.scollable_content { 
    height : 250px; 
    overflow-y : auto; 
} 

HTML

<div class="foo"> 
    <div class="bar"></div> 
    <div class="scrollable_content"> 
     <div class="someOther">...</div> 
     <div class="someOther">...</div> 
     <div class="someOther">...</div> 
     <div class="someOther">...</div> 
    </div> 
</div> 

在這裏,我爲您創建了fiddle

+0

感謝您的回覆,但問題是我需要'.bar'和scrollable_content在相同的級別/深度(由於z-index操作)。 – user2324537 2013-04-26 16:40:29

+1

然後,您必須使用Javascript來控制它。否則,你可以操縱你的HTML和CSS來做你所需要的,這可能更容易。 – 2013-04-26 17:54:43

18

當您將position:fixed應用於元素時,您將它定位爲與窗口本身相關,而不是其父元素。只要父母的位置不是position:static(默認位置),您就需要使用position:absolute來定位子女相對於其父母的位置。

正如你在你的例子中所做的那樣,將position:relative應用於父.foo,然後將position:absolute應用於子女.bar。通常情況下,這會達到將.bar對齊到父級頂部的預期結果,但是由於子級內容在父級div中溢出,並且overflow-y:scroll卷軸全部子級內容也必須滾動。請參閱my Fiddle here中的頂部示例。

爲了解決這個問題,包你想在與overflow-y:scroll另一個容器,滾動和.foo刪除overflow-y:scroll防止.bar從滾動內容。

要查看您可以調整的工作示例,請參閱my Fiddle here中的底部示例。

+1

這應該被標記爲正確的答案。 – calbertts 2015-06-01 02:37:23