CookieMonster CookieMonster - 7 months ago 29
CSS Question

Float a div at the bottom right corner, but not inside footer

I'm trying to implement a "go to top" button that floats at the bottom right corner of a page. I can do this with the following code, but I don't want this button to enter the footer of my page. How can I stop it from entering the footer and stay at the top of it when user scrolls the page down to the bottom of the page?


#to-top {
position: fixed;
bottom: 10px;
right: 10px;
width: 100px;
padding: 5px;
border: 1px solid #ccc;
background: #f7f7f7;
color: #333;
text-align: center;
cursor: pointer;
display: none;


$(window).scroll(function() {
if($(this).scrollTop() != 0) {
} else {

$('#to-top').click(function() {


<div id="to-top">Back to Top</div>

Here is a drawing of how it should look like. The black vertical rectangle is a scroll bar. The "back to top" button should never enter the footer region.
enter image description here

Here is a jsfiddle.


The solution turned out to be more complicated than I thought. Here is my solution.

It uses this function to check if footer is visible on the screen. If it is, it positions the button with position: absolute within a div. Otherwise, it uses position: fixed.

function isVisible(elment) {
    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elment).offset().top;

    return y <= (vpH + st);

$(window).scroll(function() {
    if($(this).scrollTop() == 0) {
    } else if (isVisible($('footer'))) {
    } else {