I have a situation where I need a fixed-position element to stay at the top-right corner of the viewport.
Here is the HTML code:
<div class = "header">
<p>This heading has an absolute position</p>
</div>
And here is the CSS:
.header {
position: absolute;
right:10px;
top: 10px;
}
Everything works fine until I scroll right on a laptop or zoom in on a mobile device, causing the element to shift to the left.
I tried two solutions:
1. Creating a container at the top with a width of 100% and making the element relative to it. This didn't work as expected because the container didn't adjust its size when I scrolled the window.
2. Adding event listeners for both the scroll
and touchend
events.
$(window).scroll(function(){
$(".header").css({"right": "10px", "top": "10px"});
});
$(document.body).bind("touchend", function(){
$(".header").css({"right": "10px", "top": "10px"});
});
I wanted the element to always maintain the same position relative to the viewport during any event, but this approach also failed. It seems that the CSS only positions the element based on the original viewport.
Is there a simple and effective solution to this problem?