DEV Community

Cover image for One Line - Sticky Header using CSS

One Line - Sticky Header using CSS

Akhil Arjun on August 04, 2020

How many times have we come across a situation where you want the header of a website to remain on top of everything even if you scroll past it. ...
Collapse
 
gsarig profile image
Giorgos Sarigiannidis • Edited

position:sticky is great and I use it whenever I can instead of a JavaScript solution. One caveat that you need to consider, though, is that it won't work if a parent element has an overflow:hidden;

Sometimes this might be a deal-breaker.

Collapse
 
akhilarjun profile image
Akhil Arjun

Yeah but the whole point of using sticky is when we have a scrollable element. So if we have overflow hidden. We should always go for position:absolute

Collapse
 
gsarig profile image
Giorgos Sarigiannidis • Edited

A not so rare scenario of those two conflicting would be to have a container at the top of your DOM (e.g. right after the <body>) with an overflow: hidden; in order to avoid vertical scrollbars (caused by some burger menu or whatever). Then, deeper in the DOM you might want to have your sticky element.

In that scenario, you would need to either figure another way to get rid of the vertical scrollbars or use JavaScript to stick the element. It doesn't matter if the container only has its overflow-x set to hidden and not overflow-y; it will mess with the child element's position: sticky anyway.

Collapse
 
sirawit profile image
Dragodzs

wow, that awesome!

Collapse
 
akhilarjun profile image
Akhil Arjun

Thanks mate πŸ•ΊπŸ‘Ύ

Collapse
 
majurgens profile image
majurgens • Edited

This was so super simple, I implemented it immediately.

However, I have this one page where I cannot make this work properly. I cannot work out what is going wrong. See
https://www.edcint.co.nz/cgi-bin/webalbum_search.cgi?searchterms=.&mode=search&searchfile=.webalbum_search_data_public.conf_2&albumtophtmldir=%2Fpublic%2Fdata%2F&resultnumber=0&linkback=%2Fpublic%2Fdata%2Findex.shtml&modtime=0&shortform=n&submit=&approxsearch=1&showimages=1&showvideos=1&showfolders=1&showwithcomments=1&showwithnocomments=1&imageheight=200&displayimageinfo=1&maxresults=10&modtimedays=0&ssdelay=15

The header seems to come and go as you scroll down the page. Once you reach the bottom of page (lazy loading and infinite scroll are in play here), then the header works ok.

In a related page, that uses a lot of the same code (same lazy loading and infinite scroll), it works just fine
edcint.co.nz/public/data/scenery (copy and paste, don't click this link)

Any ideas?

Collapse
 
mbaapohz profile image
Mbaapoh

Am glad, I found this

Collapse
 
akhilarjun profile image
Akhil Arjun

Glad it helps πŸ•ΊπŸ‘Ύ

Collapse
 
donwiss profile image
Don Wiss

This is beautifully simple. But one is left with the problem of jumping to an anchor on the page is now off.