Fancy sprucing up your website with a snazzy sticky navigation bar, but the thought of diving into JavaScript makes you want to leg it? Fear not! Today, we’ll show you how to create a sticky nav bar using nothing but CSS.
Looking for some more hands-on assistance? Fenix Creative can help.
Step 1: The HTML
First things first, let’s sort out the basic structure. Pop this into your HTML file:
<header class="sticky-header">
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
Step 2: The CSS
Now, here’s where the magic happens. Add this CSS to your stylesheet:
.sticky-header {
position: sticky;
top: 0;
background-color: #f8f8f8;
padding: 10px 0;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
nav ul {
list-style-type: none;
padding: 0;
margin: 0;
display: flex;
justify-content: space-around;
}
nav ul li a {
text-decoration: none;
color: #333;
font-weight: bold;
}
That’s it! You’ve got yourself a sticky navigation bar that’ll follow your visitors as they scroll.
The Secret Sauce
The key ingredient here is the position: sticky
property. Once the page scrolls past the nav’s original position, it’ll cling to the top of the viewport like it’s been superglued there thanks to top: 0
. Feel free to play around with the colours, padding, and shadows to match your site’s style.
Why Bother?
A sticky nav bar isn’t just a pretty face. It’s practical too! It keeps your main navigation easily accessible, reducing user frustration and potentially lowering bounce rates. It’s like having a helpful shop assistant who follows you around the store, but in a less creepy way.
Here’s a working pen:
See the Pen Sticky Navigation – Pure CSS by Alex Chapman (@Alex-Fenix-Creative) on CodePen.
Wrapping Up
There you have it! A sticky navigation bar using nothing but CSS. It’s so simple, you’ll wonder why you ever thought you needed JavaScript for this.
Remember, a well-designed website isn’t just about looking good – it’s about creating a smooth, intuitive experience for your visitors. And sometimes, the simplest solutions are the best.
Happy coding, and may your websites be sticky in all the right places!
P.S. If you’re feeling a bit overwhelmed by all this web design stuff, why not let the professionals handle it? We’ll be chuffed to bits to help you create a top-notch website, complete with all the bells and whistles. Get a Fenix Creative Website today!