Ask any question about Tailwind CSS here... and get an instant response.
Post this Question & Answer:
How can I create a sticky header that changes color on scroll with Tailwind? Pending Review
Asked on Apr 17, 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 detecting scroll events. Tailwind provides "sticky" positioning, which keeps the header fixed at the top of the viewport, while JavaScript can handle the color change.
<!-- BEGIN COPY / PASTE -->
<header class="sticky top-0 bg-white transition-colors duration-300" id="header">
<div class="p-4">
<h1 class="text-xl font-bold">My Sticky Header</h1>
</div>
</header>
<script>
window.addEventListener('scroll', function() {
const header = document.getElementById('header');
if (window.scrollY > 50) {
header.classList.add('bg-blue-500');
header.classList.remove('bg-white');
} else {
header.classList.add('bg-white');
header.classList.remove('bg-blue-500');
}
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
- The "sticky" utility class keeps the header at the top of the viewport.
- JavaScript is used to toggle between "bg-white" and "bg-blue-500" based on scroll position.
- Ensure the "transition-colors" and "duration-300" classes for smooth color transitions.
- Test the scroll threshold (e.g., 50px) to fit your design needs.
Recommended Links:
