我正在尝试修复一个div,使其始终保持在屏幕顶部,使用:
position: fixed;
top: 0px;
right: 0px;
然而,div位于居中的容器内。当我使用position:fixed时,它会相对于浏览器窗口修复div,例如它位于浏览器的右侧。相反,它应该相对于容器固定。
我知道position:absolute可以用来固定相对于div的元素,但是当您向下滚动页面时,元素会消失,并且不会像position:fixed那样固定在顶部。
有没有破解或解决方法来实现这一点?
我创建了一个jsfiddle来演示这是如何使用转换的。
HTML
<div class="left">
Content
</div>
<div class="right">
<div class="fixedContainer">
X
</div>
Side bar
</div>
CSS
body {
margin: 0;
}
.left {
width: 77%;
background: teal;
height: 2000px;
}
.right {
width: 23%;
background: yellow;
height: 100vh;
position: fixed;
right: 0;
top: 0;
}
.fixedContainer {
background-color:#ddd;
position: fixed;
padding: 2em;
//right: 0;
top: 0%;
transform: translateX(-100px);
}
jQuery
$('.fixedContainer').on('click', function() {
$('.right').animate({'width': '0px'});
$('.left').animate({'width': '100%'});
});
https://jsfiddle.net/bx6ktwnn/1/