dhairyashah
Portfolio

Mar 6th, 2022

Sticky navbar Vanilla and Tailwind CSS

Author Picture

Dhairya Shah

Software Engineer

Many of us have noticed, a sticky navigation bar on many websites including this blog…

demo

Here in the GIF, as you can see Table of contents is stuck to the top of the page.

The only purpose of keeping a sticky navbar looks attractive and makes little accessible.

So, you wanna add a sticky navbar to your website?


Let’s get started with Vanilla CSS ✌️

<div class="container">
  <h1 class="text">stickattop</h1>
</div>
<img src="https://images.unsplash.com/photo-1646498749176-b4ddb3b3b4a7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=872&q=80" alt="catimg" class="img">
<img src="https://images.unsplash.com/photo-1646497795650-58de9c4fd44f?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=772&q=80" class="img"/>

It’s time for CSS 😍

.container{
  position: fixed;
  top: 0;
  width: 100%;
  background: #1e293b;
}
.text{
  text-align: center;
  text-transform: uppercase;
  font-weight: 900;
  letter-spacing: 0.05em;
  color: white;
}
<div class="container">
  <h1 class="text">stickattop</h1>
</div>
<img src="https://images.unsplash.com/photo-1646498749176-b4ddb3b3b4a7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=872&q=80" alt="catimg" class="img">
<img src="https://images.unsplash.com/photo-1646497795650-58de9c4fd44f?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=772&q=80" class="img"/>
body{
  margin: 0;
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.container{
  position: fixed;
  top: 0;
  width: 100%;
  background: #1e293b;
}
.text{
  text-align: center;
  text-transform: uppercase;
  font-weight: 900;
  letter-spacing: 0.05em;
  color: white;
}

.img{
  width: 100%;
  height: auto; 
}

Output - Vanilla CSS

See the Pen by Dhairya Shah (@dhairyathedev) on CodePen.


Let’s go with Tailwind CSS 😎

<div class="top-0 sticky bg-slate-800 text-white py-4">
  <h1 class="uppercase font-black text-center text-3xl tracking-wider">stickattop</h1>
</div>
<img src="https://images.unsplash.com/photo-1646498749176-b4ddb3b3b4a7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=872&q=80" alt="catimg">
<img src="https://images.unsplash.com/photo-1646497795650-58de9c4fd44f?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=772&q=80" />

Output - Tailwind CSS

See the Pen by Dhairya Shah (@dhairyathedev) on CodePen.


🌏 Let’s connect

Support me with a coffee

Stay tuned for the next article. Stay safe and Happy Coding!