No, this is not about using position: fixed by default. Take a look at this page as example, scroll down, and see the top-left. Notice the issue metadata stick on top? As far as I know there is no pure CSS for this task, it uses onscroll to do the job.
Here is the source code and you can play with jsFiddle, try the auto-scroll button.
I didn’t invent this, the original code is from an answer1 on Stack Overflow, and that seems to be from Stack Overflow’s code, but with a few of my own modifications. The code requires jQuery.
The #sticky-anchor is the most important part, it does two things:
Providing an offset reference
We can compare with anchor and know if visitor scrolls down far enough. If so, the #sticky would be applied with an CSS class .sticky, which makes it sticky to the page; if not, then remove the CSS class to revert back the original style. This way make the code more cleaner.
Providing a blank filler2
When sticky is activated, the anchor will be given a height so it can fill up the space the sticky part was occupied. If you don’t do so, the element below sticky part would be pulled up by the outer height of sticky part.
z-index is better to be applied since other elements may have that, make sure the number is high enough so #sticky would be on top of others.
[1] | I think it is a better (correct) answer to that question, too bad no one vote it up. |
[2] | This wasn’t part of my original code, a few comments mentioned there is a “jumpy effect” or “jarring transition”, when the sticky just being activated. I’d provided a thought and even a quick solution using additional CSS rules. I didn’t update the code and now I’ve incorporated that into the code after being asked about that again. I think the comments are dragging too long, even I wouldn’t want to dig into them to see if anyone else has the same problem. I will be deleting some comments regarding this issue and probably some others to keep them as clean as possible. (2016-02-14T03:30:05Z) |
Thanks so much for this! I went ahead and created a jquery plugin based on your solution. Check it out and let me know what you think! https://github.com/dubroe/sticky-div
ReplyDelete