I'd like to use the CSS property position:fixed to fix the position of an element but at the same time prevent the element from being positioned over my footer when the user scrolls to the bottom of the page. Is there a way of stopping an element from showing over a footer in this way?
views:
73answers:
3Add some extra margin-bottom
to your footer so the user can scroll past the bottom a bit so your footer can clear the fixed element.
As long as all the elements are positioned (absolute or relative) you can use the z-index
attribute. The default value is 0, so give your footer a higher value and it will appear above the other content.
If you want the element to be fixed sometimes but not others you will need to use JavaScript to add/remove position:fixed
First of all set the element without position:fixed
so that it appears in the page above the footer where you want it once scrolled to the bottom.
Then set a css class that when added to the element fixes its position, something like:
div#sometimesfixed.fixed
{
position:fixed;
bottom: 0px;
}
The following code uses jquery, detects the scroll position on the page, and adds/removes the fixed
class accordingly:
$(window).scroll(function (event) {
var windowTop = $(this).scrollTop();
if (windowTop >= $("#footer").offset().top) {
$("div#sometimesfixed").addClass("fixed");
} else {
$("div#sometimesfixed").removeClass("fixed");
}
});