固定位置但相对于集装箱

固定位置但相对于集装箱

我在试着修复div因此,它总是粘在屏幕的顶部,使用:

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

但是,div在一个居中的容器里。当我用position:fixed它修复了div相对于浏览器窗口,例如它相对于浏览器的右侧。相反,它应该相对于容器进行固定。

我知道position:absolute可以用于修复相对于div,但是当您向下滚动页面时,元素就会消失,不会像下面这样粘在顶部position:fixed.

是否有一个黑客或解决办法来实现这一点?


喵喔喔
浏览 314回答 3
3回答

摇曳的蔷薇

实际上,这是有可能的,而公认的答案只涉及集中化,这是相当直截了当的。而且,您真的不需要使用JavaScript。这将允许您处理任何场景:设置一切,如果您想要定位:绝对在一个位置:相对容器,然后在div内创建一个新的固定位置divposition: absolute,但是不设置其顶部和左侧属性。然后,它将被固定在你想要的任何地方,相对于容器。例如:/* Main site body */.wrapper {&nbsp; &nbsp; width: 940px;&nbsp; &nbsp; margin: 0 auto;&nbsp; &nbsp; position: relative; /* Ensure absolute positioned child elements are relative to this*/}/* Absolute positioned wrapper for the element you want to fix position */.fixed-wrapper {&nbsp; &nbsp; width: 220px;&nbsp; &nbsp; position: absolute;&nbsp; &nbsp; top: 0;&nbsp; &nbsp; left: -240px; /* Move this out to the left of the site body, leaving a 20px gutter */}/* The element you want to fix the position of */.fixed {&nbsp; &nbsp; width: 220px;&nbsp; &nbsp; position: fixed;&nbsp; &nbsp; /* Do not set top / left! */}<div class="wrapper">&nbsp; &nbsp; <div class="fixed-wrapper">&nbsp; &nbsp; &nbsp; &nbsp; <div class="fixed">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Content in here will be fixed position, but 240px to the left of the site body.&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div></div>可悲的是,我希望这条线能解决我和Android的问题WebKit呈现框影模糊像素作为固定位置元素的边距,但它似乎是一个错误。不管怎样,我希望这能帮上忙!
打开App,查看更多内容
随时随地看视频慕课网APP