Ask any question about Tailwind CSS here... and get an instant response.
Post this Question & Answer:
How can I use Tailwind CSS to create a sticky header that changes color on scroll?
Asked on May 15, 2026
Answer
To create a sticky header that changes color on scroll using Tailwind CSS, you can use Tailwind's utility classes for positioning and JavaScript for the scroll effect. Tailwind provides the "sticky" class to keep the header fixed at the top, and you can change the background color using JavaScript.
<!-- 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');
} else {
header.classList.add('bg-white');
header.classList.remove('bg-gray-800', 'text-white');
}
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
- The "sticky" class along with "top-0" keeps the header fixed at the top of the page.
- Use "transition-colors" and "duration-300" for a smooth color transition effect.
- JavaScript is used to toggle classes based on the scroll position to change the header's background color.
- Ensure your HTML includes enough content to scroll for the effect to be visible.
Recommended Links:
