You can create a sticky navigation bar using only CSS with the position: sticky
property. This allows the navigation to remain visible at the top of the viewport as the user scrolls down the page.
Here's a complete example:
The key CSS properties that make the navigation sticky are:
position: sticky;
top: 0;
z-index: 10;
position: sticky
: Creates a positioned element that is treated as relative until it crosses a specified threshold, then treated as fixedtop: 0
: Sets the threshold at the top of the viewportz-index: 10
: Ensures the navigation stays above other content when scrollingThe position: sticky
property is supported in all modern browsers. For older browsers, you might need to use JavaScript or a fallback solution.
z-index
to ensure the navigation appears above other contentThis solution works well for most use cases and doesn't require any JavaScript, making it lightweight and performant.
You can create a navigation bar that becomes sticky only after scrolling down a certain distance using pure CSS. Here are two approaches:
The modern way to implement this is with CSS scroll-driven animations:
For better browser compatibility, here's a solution using minimal JavaScript:
transform: translateY(-100%)
animation-timeline
and animation-range
/* Initial state - hidden above the viewport */
transform: translateY(-100%);
/* Transition for smooth appearance */
transition: transform 300ms ease-in-out;
/* Visible state when scrolled */
transform: translateY(0);
The JavaScript approach is more widely compatible, but if you want a pure CSS solution and don't mind limited browser support, the first method is elegant and performs better.