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.
The element is set to 'fixed' or 'relative' depending upon whether the user has scrolled past the element. The element to be stuck is first identified and its current position on the page is calculated. This is done by adding the position of the element relative to the viewport with the current scroll position.
A pinned-down menu. The interesting rule here is the ' position: fixed ', that makes the DIV stay fixed on the screen. The ' top: 50% ' and ' right: 0 ' determine where the DIV is displayed, in this case: 50% down from the top of the window, and a constant 0px from the right.
2 Answers. Show activity on this post. Add position: relative; to container, and remove floats and add position: fixed; to the block you want to fixate. I have actually tried exactly that, except I had left:5px instead of left:5 , and then the div was positioned relatively to the page instead of its parent.
One method involves placing both divs inside one parent container. Assign position: relative to the container, then use position: absolute on one or both child divs to position them however you want within the parent.
This is now possible with CSS only, see https://stackoverflow.com/a/53832799/1482443
In case anyone needs jQuery approach, below is the original answer as it was posted 8 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/
This is possible with CSS3. Just use position: sticky
, as seen here.
position: -webkit-sticky; /* Safari & IE */ position: sticky; top: 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With