我正在尝试修复一个div,使其始终保持在屏幕顶部,使用:

position: fixed;
top: 0px;
right: 0px;

然而,div位于居中的容器内。当我使用position:fixed时,它会相对于浏览器窗口修复div,例如它位于浏览器的右侧。相反,它应该相对于容器固定。

我知道position:absolute可以用来固定相对于div的元素,但是当您向下滚动页面时,元素会消失,并且不会像position:fixed那样固定在顶部。

有没有破解或解决方法来实现这一点?


当前回答

位置:粘滞,这是一种新的定位元素的方法,在概念上类似于位置:固定。不同之处在于,在视口中满足给定的偏移阈值之前,具有position:sticky的元素在其父元素中的行为类似于position:relative。

在Chrome 56中(目前为2016年12月的测试版,2017年1月稳定):粘性现在又回来了。

https://developers.google.com/web/updates/2016/12/position-sticky

更多详情请参见“坚持你的着陆!”!位置:WebKit中的粘性土地。

其他回答

我不得不用我的客户想坐在内容区之外的广告来做这件事。我只是简单地做了下面的事情,它就像一个魅力!

<div id="content" style="position:relative; width:750px; margin:0 auto;">
  <div id="leftOutsideAd" style="position:absolute; top:0; left:-150px;">
    <a href="#" style="position:fixed;"><img src="###" /></a>
  </div>
</div>

实现相对固定位置的另一个奇怪的解决方案是将容器转换为iframe,这样固定元素可以固定到容器的视口而不是整个页面。

你可以试试我的jQuery插件FixTo。

用法:

$('#mydiv').fixTo('#centeredContainer');

检查此项:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body style="width: 1000px !important;margin-left: auto;margin-right: auto">
        <div style="width: 100px; height: 100px; background-color: #ccc; position:fixed;">
        </div>
        <div id="1" style="width: 100%; height: 600px; background-color: #800000">
        </div>
        <div id="2" style="width: 100%; height: 600px; background-color: #100000">
        </div>
        <div id="3" style="width: 100%; height: 600px; background-color: #400000">
        </div>
    </body>
</html>

是的,只要不设置固定元素的位置(顶部或左侧等),这是可能的(不过,您仍然可以使用边距设置相对位置)。西蒙·博斯(Simon Bos)不久前发布了这篇文章。

然而,不要期望固定元素与非固定亲属滚动。

请在此处查看演示。