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. Show Or, to have a navigation bar that is beneath a hero-banner to stick to the top once we scroll past it. Or even for a navigation bar to stay at the bottom of a mobile website. We have been in this sticky situation (pun intended) over and over. The time has come we solve this once and for all. The best part is, we will do it in one-line 😎 CSS
Enter fullscreen mode Exit fullscreen mode I know what you are thinking, that is two lines! OK I admit I got carried away with the one-line heading, but I assure you it is still awesome 😍 Let's see some demo's and understand how it works Demo 1: The nav-bar that just sticks Let's try and understand what is happening here. The markup I have used is pretty simple HTML
Enter fullscreen mode Exit fullscreen mode CSS
Enter fullscreen mode Exit fullscreen mode Of all that mark-up the most important two lines where all the magic happens is
Enter fullscreen mode Exit fullscreen mode What it tells the browser is to stick this element to the viewport when its top position value is 0; An element with A sticky element toggles between Now that we understood how it works let us see two more use-cases of Demo 2: Nav-bar below a hero banner. Here, the nav-bar is below the hero banner. So it acts Demo 3: Application with a sticky header and footer Notice how we have styled
1 element.
Enter fullscreen mode Exit fullscreen mode There you go! We are now officially sticky! 🐱👤✌ Do you know what else is sticky? Coffee spilled on a table! My days are fueled with coffees and only coffees. So I know, you know what we all should do 🤞 How do I stop my header from scrolling?The header component needs to be turned into a top-level container, with z-index: 1; and position: fixed; In this way it will remain sticky at the top when you are scrolling. How do I make my header stay at the top?To get the header to stay in place when scrolling, you can use CSS position: fixed; property on the header element. This will allow the header to stay at the top of the page, even when the user scrolls up or down the page. How do I get to the top of the page without scrolling?Keyboard shortcuts: On most web browsers, pressing the "Home" key on your keyboard will quickly scroll to the top of the page. On some laptops or keyboards, you may need to use a combination of keys, such as "Fn + Left Arrow" or "Ctrl + Home". Scrollbar: Many web pages have a scrollbar on the right side of the screen. How do I turn off scroll top?Set overflow-x to Hidden to Disable Horizontal Scroll Bar in CSS. For disabling the horizontal scrolling we can set the property overflow-x to hidden along with the height is set to 100%. Everything else remains the same. Let's see the implementation for this. |