A sticky navigation bar scrolls with the user and is constantly present for easy access. It can make a website much more dynamic and enhance the user experience.
Creating a sticky nav bar is simple and requires just only a few HTML and CSS tricks.
First establish and connect the HTML and CSS files for the project. Afterwards the nav tag should be the first component within the body tag as it would be on the very top of the webpage.
<body>
<nav>
<h2>LinkedIn</h2>
<h2>Facebook</h2>
</nav>
<img src=".your-image">
</body>
Navigation bars would sometimes contain links to other pages within the site or links to social media.
Implement some HTML content below the navigation bar, such as an image.
From there, locate the CSS file. Before the navigation bar can be manipulated, it is important to eliminate empty space bordering the content.
* {
margin: 0;
padding: 0;
}
The asterisk selects all elements within the HTML. Setting margin and padding to 0 ensures that the content takes up the whole page and leaving no white space.
For the nav bar, set the width to 100% and float whatever content it contains to the left for the horizontal appearance. Optionally, setting a distinguishable background color can assist with the screen orientation.
Set the nav position to "fixed". This will position the nav bar to the relative viewport and stay visible when the user scrolls through the page.
Finally, set the z-index of the nav bar to 2. The z-index property specifies the stacking order of the elements. The element with the highest z-index number is always in front of the element with the lower number. All elements have a natural z-index of zero, so manually setting the nav bar z-index to 2 ensures proper stacking.
nav {
background-color: aqua;
z-index: 2;
position: fixed;
width: 100%;
}
nav h2 {
float: left;
}
After completing these steps, the navigation bar will now stick to its place. Any other new content will slide underneath it as the users scroll through the page.
Now have fun creating the rest of the project!