Search code examples
htmlcssmedia-queries

Prevent overlap of sticky footer inside fixed sidebar


Our site has a fixed sidebar containing a sticky footer. This worked fine when viewed on displays where the browser height was greater than the height of the sidebar content but on smaller displays the footer was "cut off".

To remedy this, I added a media query which would change the footer to be relatively positioned inside the sidebar and set overflow: auto on the sidebar:

/* sidebar padding + menu height + footer height */
@media screen and (max-height: 580px) {
    .sidebar .footer {
        position: relative;
    }
}

Although this at least allows the full sidebar content to be viewed on smaller displays it also means we end up with a scrollbar on the sidebar which doesn't look very nice.

What I would like to happen is that if the browser viewport is smaller than the height of the sidebar content you should be able to scroll using the normal page scrollbar to view all the content.

I imagine this is possible with a media query to change the position of the sidebar but I just can't seem to figure it out.


Solution

  • I'm not sure if this can be achieved with pure CSS, since what you're describing is a media query that specifies "If the viewport is under 580px height, fix the sidebar position until a certain scroll distance, then position it statically". Scrolling is a property that goes beyond the scope of media queries.

    Building on Brad's answer - here's a quick way to do it with jQuery

    jsFiddle example

    $(document).scroll(function(){    
        if ($(window).height()<=580){
            var sidebarObj=$(".sidebar");
            var extraSidebar=sidebarObj.height()-$(window).height();        
            if ($(document).scrollTop()>extraSidebar){            
                if (sidebarObj.css("position")!="fixed"){
                    sidebarObj.css({
                        "position": "fixed",
                        "top": -extraSidebar+"px"
                    });
                }
            }
            else{
                sidebarObj.css({
                    "position": "static",
                    "top": 0+"px"
                });
            }
        }
    });