2012-06-29 62 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