2012-06-29 63 views
23

我想知道是否有人爲此找到了解決方案?滾動容器內的CSS位置元素「固定」

我要尋找一個解決方案的元件連接到一個滾動容器的頂部

HTML:

<div class="container"> 
    <div class="header">title</div> 
    <div class="element">......</div> 
    ... (about 10-20 elements) ... 
    <div class="element">......</div> 
</div> 

所有的「要素」有position:relative

容器具有以下CSS:

.container { 
    position:relative; 
    width:200px; 
    height:400px; 
    overflow-y:scroll; 
} 

我想讓標題保持在最佳狀態o容器,不管其滾動位置和滾動下面的元素。

的CSS迄今:

.header { 
    position:absolute; /* scrolling out of view :-(*/ 
    z-index:2; 
    background-color:#fff; 
} 
.element{ 
    position: relative; 
} 

所有元素都是塊元件,並且我不能移動首部中的容器的外部。 jquery在這一點上是沒有選擇的。

+0

你可以用jQuery來做到這一點。 http://www.ruturaj.net/automatic-header-stick-to-scroll-with-jquery/ –

+0

如果容器沒有相對定位,當絕對定位時,標題將位於其頂部。你的標題可以是容器的前一個兄弟(呃,「容器」現在就是這樣的「內容」)或者你的元素有自己的容器,並且容器上沒有'position:relative'? – FelipeAls

+0

@FelipeAlsacreations:職位:固定不尊重職位:親屬。它在任何時候都是對文檔進行實時固定的。 –

回答

3

在這種情況下,解決辦法是彈出滾動元件的外部標題:

<div class="header">title</div> 
<div class="container"> 
    <div class="element">......</div> 
    <div class="element">......</div> 
</div> 

雖然你應該有更好的語義元素(如果可能只是猜測這裏):

<h3>title</h3> 
<ul> 
    <li>......</li> 
    <li>......</li> 
</ul> 
5

jQuery UI添加了一個position()實用程序方法,僅用於此目的,這將使您的生活更輕鬆。

$("#someElement").position({ 
    of: //Element to position against, 
    my: //which position on the element being positioned, 
    at: //which position on the target element eg: horizontal/vertical, 
    offset: // left-top values to the calculated position, eg. "50 50" 
}); 

肯定幫了我。

15

我認爲您的解決方案通過position:sticky。看起來像position:fixed,但尊重他的父母的相對位置。

不幸的是,這是一個實驗性功能,僅在Chromium中受支持。您可以在this test page中查看更多詳情。

進入我腦海的純css解決方案是對標記進行一些更改。您可以設置一個容器,僅用於「元素」,如下所示:

<div class="cont_elements"> 
     <div class="element">......</div> 
     ..... 
</div> 

並給這個內部容器溢出。現在,你的標題頂部。

Here's a working demo

+2

請注意,目前這並不適用於Chrome,它可以在IOS中使用,但不適用於Android版Chrome。請參閱caniuse.com/#feat=css-sticky –

+0

Chrome在windows(10) - 3年半之後... – T4NK3R