How to make div fixed after you scroll to that div?
Asked Answered
G

6

88

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

If I use:

.divname {
  position: fixed;
}

The div will appear before it should appear normally. Maybe a 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.

Ginkgo answered 6/4, 2013 at 11:20 Comment(0)
C
144

This is now possible with CSS only, see https://mcmap.net/q/236591/-how-to-make-div-fixed-after-you-scroll-to-that-div


In case anyone needs jQuery approach, below is the original answer as it was posted years ago:

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

});

http://jsfiddle.net/5n5MA/2/

Crystalloid answered 6/4, 2013 at 11:31 Comment(1)
usually it is required to wrap this code with $(window).load(function () { ... }); so fixmeTop will have correct value after loading css filesRevolutionary
C
117

This is possible with CSS3. Just use position: sticky, as seen here.

position: -webkit-sticky; /* Safari & IE */
position: sticky;
top: 0;
Chamade answered 18/12, 2018 at 12:16 Comment(5)
This should obviously be changed to the best answer.Unadvised
This is not thee best answer! This is THE answer... Others are just workarounds. :DBurgage
i wish there was a way to have position absolute while also being sticky?Satire
@AkinHwan You can do that, but not with CSS only.Bret
This is not the best answer in all situations or all scenarios. If the ancestors of this element don't have height set or don't have overflow set, and for whatever reason they can't have height set or overflow unset, then this won't work. This might be the case if you are adding an element to a complicated pre existing page. It is ideal if it can be used though.Amaty
D
6

jquery function is most important

<script>
$(function(){
    var stickyHeaderTop = $('#stickytypeheader').offset().top;

    $(window).scroll(function(){
            if( $(window).scrollTop() > stickyHeaderTop ) {
                    $('#stickytypeheader').css({position: 'fixed', top: '0px'});
                    $('#sticky').css('display', 'block');
            } else {
                    $('#stickytypeheader').css({position: 'static', top: '0px'});
                    $('#sticky').css('display', 'none');
            }
    });
});
</script>

Then use JQuery Lib...

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

Now use HTML

<div id="header">
    <p>This text is non sticky</p>
    <p>This text is non sticky</p>
    <p>This text is non sticky</p>
    <p>This text is non sticky</p>
 </div>

<div id="stickytypeheader">
 <table width="100%">
  <tr>
    <td><a href="http://growthpages.com/">Growth pages</a></td>

    <td><a href="http://google.com/">Google</a></td>

    <td><a href="http://yahoo.com/">Yahoo</a></td>

    <td><a href="http://www.bing.com/">Bing</a></td>

    <td><a href="#">Visitor</a></td>
  </tr>
 </table>
</div>

<div id="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.</p>
</div>

Check DEMO HERE

Driving answered 31/12, 2014 at 10:20 Comment(0)
P
5

Adding on to @Alexandre Aimbiré's answer - sometimes you may need to specify z-index:1 to have the element always on top while scrolling. Like this:

position: -webkit-sticky; /* Safari & IE */
position: sticky;
top: 0;
z-index: 1;
Parasynapsis answered 15/10, 2020 at 17:25 Comment(3)
You could have just improved his answer or commentGilliette
I could have done that, but I don't have enough reputation points to add a comment or improve others answes.Parasynapsis
Oh sorry about, and so I'll upvoteGilliette
W
3
<script>
if($(window).width() >= 1200){
    (function($) {
        var element = $('.to_move_content'),
            originalY = element.offset().top;

        // Space between element and top of screen (when scrolling)
        var topMargin = 10;

        // Should probably be set in CSS; but here just for emphasis
        element.css('position', 'relative');

        $(window).on('scroll', function(event) {
            var scrollTop = $(window).scrollTop();

            element.stop(false, false).animate({
                top: scrollTop < originalY
                    ? 0
                    : scrollTop - originalY + topMargin
            }, 0);
        });
    })(jQuery);
}

Try this ! just add class .to_move_content to you div

Warman answered 22/2, 2017 at 9:1 Comment(1)
works like charm! if anyone needs z-index: 9999 in CSS will bring <div> element in front of other contentColumn
S
1

it worked for me

$(document).scroll(function() {
    var y = $(document).scrollTop(), //get page y value 
        header = $("#myarea"); // your div id
    if(y >= 400)  {
        header.css({position: "fixed", "top" : "0", "left" : "0"});
    } else {
        header.css("position", "static");
    }
});
Singleness answered 8/8, 2016 at 9:33 Comment(1)
This is what I needed.Manfred

© 2022 - 2024 — McMap. All rights reserved.