Jakov Mikić Jakov Mikić - 2 months ago 10
CSS Question

How to make div fixed after you scroll to that div?

How to make a div remain fixed after you scroll to that div?
I have a div that is later in the page and you need to scroll to get to that div.

If I use

position: fixed;

div will appear before it should appear normally.
Maybe the good example of what I need is second ad on 9gag. If your screen resolution is low enough, you won't see that ad after you load the front page, but after you scroll down, you'll see the second ad and it will remain fixed while you scroll down.


I know this is tagged html/css only, but you can't do that with css only. Easiest way will be using some jQuery.

var fixmeTop = $('.fixme').offset().top;       // get initial position of the element

$(window).scroll(function() {                  // assign scroll event listener

    var currentScroll = $(window).scrollTop(); // get current position

    if (currentScroll >= fixmeTop) {           // apply position: fixed if you
        $('.fixme').css({                      // scroll to that element or below it
            position: 'fixed',
            top: '0',
            left: '0'
    } else {                                   // apply position: static
        $('.fixme').css({                      // if you scroll above it
            position: 'static'