简体   繁体   中英

Stick div to bottom of browser window

I have a div that I would like to stick to the bottom of the browser window (the actual browser window not the page). The div needs to stay at the bottom of the browser window while the user scrolls.

Right now, the div will stick to the bottom of the window on the first initial scroll but it will not re-position each time there is a new scroll. Here is what I have for my jQuery:

$(window).scroll(function () { 
    var bHeight = $(window).height();
    $('.test').css({
        top: bHeight - 77 + 'px'
    });
});

Here is a jsfiddle http://jsfiddle.net/3ecx7zp9/1/

This can simply be done in CSS. Remove all your JavaScript, and do the following:

position: fixed;
bottom: 77px;

Fiddle

Have you considered using a fixed position div? set position: fixed and bottom: 77px

However if you must use a jQuery solution change your code to this

$(window).scroll(function () { 
    var bHeight = $(window).height();
    var offset = $(window).scrollTop();
    $('.test').css({
        top: bHeight + offset - 77 + 'px'
    });
});

http://jsfiddle.net/3ecx7zp9/6/

That takes into account how far you have scrolled and will set the position of the div accordingly

In your CSS use position: fixed; instead of position: absolute; .

http://jsfiddle.net/3ecx7zp9/4/

Do you want to use position: fixed; ?

https://jsfiddle.net/js7tadve/1/

干得好:

  <div class="test" style="position: fixed; width: 100%; height: 77px; background-color: #333;left:0;bottom:0"></div> 

Check if the below link will work with you.

Fiddle

#footer {
position: fixed;
bottom: 0;
height: 77px;
width: 100%;
background-color: #333;
}

This is precisely what position: fixed was designed for:

#footer {
    position: fixed;
    bottom: 0;
    width: 100%;
}

Here's the fiddle: http://jsfiddle.net/uw8f9/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM