Reputation: 1146
I have a page that uses Javascript to fix the header to the top of the page (thus removing the banner) when you scroll past the bottom of the banner (about 200px down page).
On this website I've been using containers that have the position:inherit;
property set to contain each part of the page. These then have a relatively positioned element inside them so I can place all my absolutely positioned elements where I like.
My problem is that id="content"
keeps jumping to the top of the page when the Javascript changes id="header"
to position:fixed;
.
I have tried absolutely positioning id="content"
and setting its top value but it wouldn't work and I'm a bit stuck.
Here is a very simplified version of the HTML:
<body>
<div id="page"> <!--inherit-->
<a id="banner"></a> <!--inherit-->
<div id="header"> <!--inherit-->
<div id="lang"> <!--relative-->
<ul>...</ul> <!--inherit-->
<other divs> <!--absolute-->
</div>
<div id="nav"> <!--relative-->
<ul>..</ul> <!--inherit-->
<a id="userbutton"></a> <!--absolute-->
</div>
</div
<div id="content0"> <!--inherit-->
<div id="content"> <!--relative-->
<PAGE CONTENT> <!--absolute-->
</div>
</div>
<div id="footer"></div>
</div>
</body>
Here is my javascript:
var bannerheight // Glob var
window.onload = function() {
window.bannerheight = $('#bannerimg').height();
checkOffset();
};
window.onscroll = function(oEvent) {
checkOffset();
}
function checkOffset() {
if (window.pageYOffset >= window.bannerheight) {
document.getElementById("header").style.position = "fixed";
document.getElementById("banner").style.display = "none";
document.getElementById("padding").style.height = window.bannerheight+"px";
}
else {
document.getElementById("header").style.position = "inherit";
document.getElementById("banner").style.display = "block";
document.getElementById("padding").style.height = "0px";
}
}
and here is the relevant CSS:
#page {
margin:0px auto;
}
#lang {
position:relative;
}
#nav {
position:relative;
margin:0px auto;
}
#content0 {
height:800px;
}
#content {
position:relative;
margin:0px auto;
}
Upvotes: 0
Views: 1914
Reputation: 11
Try giving the content div a "margin-top" and set it to the number of pixels that the page is "jumping". Then when you scroll up and reset the position, undo the margin-top back to zero.
I've tested this and it solved my jumping issue.
Upvotes: 1
Reputation: 57729
I'm not sure what you expect as output but position: fixed
works on the document, globally. It not only ignores element flow (like position: absolute
) but it also ignores scrolling.
position: absolute
is relative to it's offset parent which can be an item with position: relative
.
You typically only want to use position: fixed
if something needs to stick to the window, like a little popup that scrolls with as you go down the page. The Facebook header is a good example. Their header bar is fixed to the top of the window and stays there even if you scroll.
Upvotes: 0