Piotr Ciszewski
Piotr Ciszewski

Reputation: 1791

Element stays on the top when the page is scrolled down, but always under the header

Please see this jsfiddle here: jsfiddle.

I want the red element on the right to stay always on top, but never cover the header. So when the page is not scrolled down it is somewhere, for example 200px from top. When I scroll down and the top of the window touches it, it comes down along with the page, glued to the top. The code I used is here:

<header>header</header>
<div class="overflow">
    <div class="left">
        Some content here, doesn't matter what... 
    </div>

    <aside>
        This is a key element
    </aside>
</div>

And CSS:

body {margin:0; padding:0}
header {width:100%; height:200px; background-color:#994499; margin-bottom:30px;}
.overflow {overflow:hidden; width:450px; margin:0 auto;}
.left {float:left; width:300px; background-color:yellow; margin-right:20px; height:1000px;}
aside {position:fixed; top:230px; margin-left:350px; background-color:red;}

Upvotes: 1

Views: 1128

Answers (1)

KennyGHanson
KennyGHanson

Reputation: 104

You can use the "sticky navbar" technique for this functionality, if you don't mind jQuery.

The trick being to absolutely/relatively position the element opposed to fixed, then apply a fixed class on scroll.

JSFiddle

$(function () {
    var elem = $('aside'),
        elemTop = elem.offset().top;
    $(window).scroll(function () {
        elem.toggleClass('fixed', $(window).scrollTop() > elemTop);
    }).scroll();
});

Upvotes: 4

Related Questions