Ask any question about Tailwind CSS here... and get an instant response.
Post this Question & Answer:
How can I use Tailwind to create a sticky header that changes color on scroll?
Asked on Jan 26, 2026
Answer
To create a sticky header that changes color on scroll using Tailwind CSS, you'll need to combine Tailwind's utility classes for positioning and background colors with a bit of JavaScript to handle the scroll event.
<!-- BEGIN COPY / PASTE -->
<header class="sticky top-0 bg-white transition-colors duration-300" id="header">
<nav class="p-4">
<h1 class="text-xl font-bold">My Website</h1>
</nav>
</header>
<script>
window.addEventListener('scroll', function() {
const header = document.getElementById('header');
if (window.scrollY > 50) {
header.classList.add('bg-gray-800', 'text-white');
header.classList.remove('bg-white', 'text-black');
} else {
header.classList.add('bg-white', 'text-black');
header.classList.remove('bg-gray-800', 'text-white');
}
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
- The "sticky" class keeps the header fixed at the top while scrolling.
- Use "transition-colors" and "duration-300" for smooth color transitions.
- JavaScript toggles classes based on scroll position to change the header's color.
- Ensure the header's height doesn't interfere with content visibility when sticky.
Recommended Links:
