绝对和固定定位在一起

Man*_*olo 9 html css css-position

正如您在此页面中看到的:http://pitchfork.com/,右侧有一些音频元素.我检查了他们,他们似乎有绝对的定位.但如果你向下滚动,你会发现它们是固定的.

怎么能实现这种行为?可以是绝对和固定定位的元素吗?

Man*_*olo 11

这是我找到的唯一方法:就像@DreamTek 所说:

<div id="relative-layer">
    <div id="fixed-layer">
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

并在样式文件中:

#relative-layer {
    position:relative;
}

#fixed-layer {
    position: fixed;
    margin-top: 10px;
    margin-left: 10px;
}
Run Code Online (Sandbox Code Playgroud)

因为使用topright规则相对于窗口定位层,但如果使用margin-topmargin-left它相对于父层定位。

JSFIDDLE:http : //jsfiddle.net/9HQ4b/1/


Dre*_*TeK 7

创建一个很酷的固定滚动侧边栏,没有javascript和几行css.

固定垂直div,灵活的水平定位.

下面小提琴中的固定div似乎相对于容器定位,但这只是一种幻觉.

固定的 DIVS总是与屏幕相对应.

绝对的潜水者总是出现相对于他们最近的位置:相对的'容器.

HTML

<div class="Wrap">WRAP</div>
<div class="Fixed">FIXED</div>
Run Code Online (Sandbox Code Playgroud)

CSS

.Wrap{
    background:#ccc;
    width:600px;
    height:300px;
    margin:0 auto;
}
.Fixed{
    position:fixed;
    top:20px;
    right:50%; /* this is the trick to make the fixed div appear absolute */
    background:#333;
    height:100px;
    width:50px;
    margin-right:-360px; /*Must be half of container width plus desired positioning*/
}
Run Code Online (Sandbox Code Playgroud)

通过使用负边距和固定宽度容器来实现同时出现绝对和固定的div的错觉.

http://jsfiddle.net/9HQ4b/2/

小网站版本适用于较小宽度的屏幕.

http://jsfiddle.net/9HQ4b/3/