简体   繁体   中英

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;}

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();
});

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