Best way to create a sticky nav bar?


#1

Hi,

I am wondering what would be the best way to create a sticky top navigation bar? I’ve read that the position: sticky is not supported by all browsers.

I have a main navbar which is under a smaller one, which I would like the main navbar to be sticky when the page scrolls. I’ve tried position: fixed, but when it scrolls, it leaves a gap where the bar above it is.

What would be the best way to create a sticky navbar under another?

Thanks


#2

support depends on the elements involved. You might want to read this:

https://caniuse.com/#search=position%3A%20sticky

Then, if your planned nav bar falls into an unsupported category, show the code that you have developed thus far so we don’t waste time guessing about your context (the complete structure of your layout).


#3

Position sticky is the best way as position fixed is nearly always problematic.

It degrades perfectly in older browsers and they won’t know it was supposed to be sticky.

You still need the prefixed version for iOS but the benefit is that sticky works much better on mobile than position fixed does anyway.


#4

Thanks for the reply.

I tried position: fixed, but I can’t get it to start from the top of the page after the top nav bar has scrolled - it leaves a space at the top.

I’ve also tried position: sticky and it doesn’t do anything in Chrome. Do I need some JS with it too?

This is the fiddle I have:
https://jsfiddle.net/toolman/d9j45grs/7/


#5

There is one site where I have been using it for years.
I took the attitude of “What’s the worst thing that could happen if a browser does not support it?”
Well, the don’t get a sticky nav bar, but they still have a nav bar and that’s good enough.


#6

You need to give it a top value so it knows where to stick.
Try top: 0 to stick at the very top of the page.
Also you will want the -webkit- prefix for Safari support.


#7

You didn’t say where you wanted it to stick.

header.header-blue {
	background: #064882;
	padding: 15px 0;
	margin-bottom: 20px;
	color: #fff;
	font-size: 18px;
	box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2);
	border-bottom: 1px solid #00111f;
	z-index: 1000;
	position: -webkit-sticky;
	position: sticky;
	top:0;
}
Edit:

Beaten By Sam :slight_smile:


#8

Thanks everyone :slight_smile:
The top: 0px worked. I’ve also added

	position: -webkit-sticky;
	position: -moz-sticky;
	position: -ms-sticky;
	position: -o-sticky;

#9

-webkit- is really the only one you need for current browsers and be sure to include the non prefixed version last.
Also in css where you have a 0 value, don’t include the units, zero is zero in any unit of measurement.


#10

Yes just to re-iterate what Sam said the only prefix available is webkit. Other browsers either implement it or they don’t.

https://caniuse.com/#search=sticky


#11

Great, thank you for the tips!