I want to make the navigation bar stick to the top of the viewport once a user scrolls the page, but it's not working and I have no clue why. If you can please help, here is my HTML and CSS code:
.container { min-height: 300vh; } .nav-selections { text-transform: uppercase; letter-spacing: 5px; font: 18px "lato",sans-serif; display: inline-block; text-decoration: none; color: white; padding: 18px; float: right; margin-left: 50px; transition: 1.5s; } .nav-selections:hover{ transition: 1.5s; color: black; } ul { background-color: #B79b58; overflow: auto; } li { list-style-type: none; }
<main class="container"> <nav style="position: sticky; position: -webkit-sticky;"> <ul align="left"> <li><a href="#/contact" class="nav-selections" style="margin-right:35px;">Contact</a></li> <li><a href="#/about" class="nav-selections">About</a></li> <li><a href="#/products" class="nav-selections">Products</a></li> <li><a href="#" class="nav-selections">Home</a></li> </ul> </nav> </main>
position: sticky; A sticky element toggles between relative and fixed , depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).
If you really want position: sticky to work on all modern browsers, then you should consider not using overflow: hidden on the <body> or any wrapper surrounding the main content, but rather put a wrapper around elements that will overflow the viewport. Then, those wrappers should use overflow: hidden.
A sticky element is always relatively positioned to its parent (much like position: absolute; ). This means that these elements will stick and unstick only within the bounds of its parent element, not the viewport (making our job easier); it also means that the thresholds are marked by the edges of the parent.
The simple solution is to remove or unset overflow-x: hidden; from every ancestor of the element you want to have position: sticky; . Then you can have overflow-x: hidden; on the body and it will work!
Check if an ancestor element has overflow set (e.g. overflow:hidden
); try toggling it. You may have to inspect the DOM tree higher than you expect =).
This may affect your position:sticky
on a descendant element.
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