Reputation: 848
So I have a supposedly fixed-positioned element that I want to fix on the viewport at the top-right corner.
This is the HTML:
<div class = "header">
<p>This is a heading with an absolute position</p>
</div>
and the CSS:
.header {
position: absolute;
right:10px;
top: 10px;
}
It works as desired until you scroll to right with a laptop or zoom in with a mobile device. Either these two events will shift the element to left depending on the extent the events are.
I came up with 2 solutions:
1: make a div container at the top with the width as 100% and make the element relative to the container. This failed as when I scroll the window the container does not extend accordingly
2: add an event listener listening to two events scroll
and touchend
.
$(window).scroll(function(){
$(".header").css({"right": "10px", "top": "10px"});
});
$(document.body).bind("touchend", function(){
$(".header").css({"right": "10px", "top": "10px"});
});
I wanted to update the element at every selected event and make it always the same position relative to the viewport but this method failed too. Seems like the css will only position the element according to the original viewport
Is there a simple yet efficient solution for this issue?
Upvotes: 0
Views: 1012
Reputation: 9118
If you are trying to anchor something to the viewport, use a fixed position:
position: fixed;
Upvotes: 2