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

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

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

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

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


当前回答

当您使用position:fixed CSS规则并尝试应用top/left/right/bottom时,它会相对于窗口定位元素。

解决方法是使用边距财产,而不是上/左/右/下

其他回答

当您使用position:fixed CSS规则并尝试应用top/left/right/bottom时,它会相对于窗口定位元素。

解决方法是使用边距财产,而不是上/左/右/下

检查此项:

<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>
/* html */

/* this div exists purely for the purpose of positioning the fixed div it contains */
<div class="fix-my-fixed-div-to-its-parent-not-the-body">

     <div class="im-fixed-within-my-container-div-zone">
          my fixed content
     </div>

</div>



/* css */

/* wraps fixed div to get desired fixed outcome */
.fix-my-fixed-div-to-its-parent-not-the-body 
{
    float: right;
}

.im-fixed-within-my-container-div-zone
{
    position: fixed;
    transform: translate(-100%);
}

如果您使用JavaScript,这是可能的。在本例中,jQuery插件Sticky Kit:

使用纯CSS,你无法做到这一点;至少我没有。然而,您可以非常简单地使用jQuery来实现。我会解释我的问题,稍加改动你就可以使用了。

因此,首先,我希望我的元素有一个固定的顶部(从窗口顶部),以及一个从父元素继承的左侧组件(因为父元素居中)。要设置左侧组件,只需将元素放到父元素中,并设置父元素的位置:relative。

然后,您需要知道当滚动条位于顶部(y为零滚动)时,元素距离顶部的距离是多少;还有两种选择。首先,它是静态的(一些数字),或者必须从父元素中读取它。

在我的例子中,它距离顶部静态图像150像素。所以,当你看到150时,它是当我们没有滚动时,元素从顶部开始的数量。

CSS

#parent-element{position:relative;}
#promo{position:absolute;}

jQuery

$(document).ready(function() { //This check window scroll bar location on start
    wtop=parseInt($(window).scrollTop());
    $("#promo").css('top',150+wtop+'px');

});
$(window).scroll(function () { //This is when the window is scrolling
    wtop=parseInt($(window).scrollTop());
    $("#promo").css('top',150+wtop+'px');
});