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

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

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

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

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


当前回答

检查此项:

<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>

其他回答

我不久前做过类似的事。我对JavaScript很陌生,所以我相信你可以做得更好,但这里有一个起点:

function fixxedtext() {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        if (document.body.offsetWidth > 960) {
            var width = document.body.offsetWidth - 960;
            width = width / 2;
            document.getElementById("side").style.marginRight = width + "px";
        }
        if (document.body.offsetWidth < 960) {
            var width = 960 - document.body.offsetWidth;
            document.getElementById("side").style.marginRight = "-" + width + "px";
        }
    }
    else {
        if (window.innerWidth > 960) {
            var width = window.innerWidth - 960;
            width = width / 2;
            document.getElementById("side").style.marginRight = width + "px";
        }
        if (window.innerWidth < 960) {
            var width = 960 - window.innerWidth;
            document.getElementById("side").style.marginRight = "-" + width + "px";
        }
    }
    window.setTimeout("fixxedtext()", 2500)
}

您需要设置宽度,然后它会获取窗口宽度并每隔几秒更改边距。我知道它很重,但它有效。

只需将顶部和左侧样式从固定位置div

<div id='body' style='height:200%; position: absolute; width: 100%; '>
    <div id='parent' style='display: block; margin: 0px auto; width: 200px;'>
        <div id='content' style='position: fixed;'>content</div>
    </div>
</div> 

#content div将位于父div所在的位置,但将固定在那里。

如果你改变立场,你有一个解决方案:固定;定位:粘性;

所以你的代码应该是:

position: sticky;
top: 0;
right: 0;

现在其他潜水艇不会滑到下面。

2019解决方案:您可以使用位置:粘性属性。

下面是一个示例CODEPEN,演示了用法以及它与位置的区别:fixed。

其行为说明如下:

具有粘性位置的元素基于用户的滚动位置来定位。它的作用基本上类似于position:relative,直到元素滚动超过特定偏移量,在这种情况下,它变成position:fixed。当它向后滚动时,它将返回到其先前(相对)位置。它影响页面中其他元素的流动,即占据页面上的特定空间(就像位置:相对)。如果它是在某个容器内定义的,则相对于该容器定位。如果容器有一些溢出(滚动),根据滚动偏移量,它将变为位置:固定。

因此,如果您想在容器内实现固定功能,请使用粘性。

我也有同样的问题,我们的一个团队成员给了我一个解决方案。为了允许div定位并相对于其他div,我们的解决方案是使用父容器包装固定div和滚动div。

.容器{位置:相对;挠曲:1;显示:柔性;}.修复{位置:绝对;}<div class=“container”><div class=“scroll”></div><div class=“fix”></div></div>