
Alerts And Toasts in TailwindCSS
? Alerts and Toasts with Tailwind CSS
Alerts and toasts are used to show messages or notifications to users — alerts usually appear inline, toasts are often small popup messages that disappear automatically.
Alerts
Alerts are simple messages that can have different types (success, error, warning, info).
Basic Alert Example
<div class="p-4 mb-4 text-sm text-green-700 bg-green-100 rounded-lg" role="alert"> <span class="font-medium">Success!</span> Your operation completed successfully.</div><div class="p-4 mb-4 text-sm text-red-700 bg-red-100 rounded-lg" role="alert"> <span class="font-medium">Error!</span> Something went wrong.</div><div class="p-4 mb-4 text-sm text-yellow-700 bg-yellow-100 rounded-lg" role="alert"> <span class="font-medium">Warning!</span> Be cautious about this.</div><div class="p-4 mb-4 text-sm text-blue-700 bg-blue-100 rounded-lg" role="alert"> <span class="font-medium">Info:</span> Here’s some information.</div>
Toasts
Toasts are temporary, floating notifications that usually appear at the bottom or top corner of the screen.
Simple Toast Example
<!-- Toast Container --><div id="toast-container" class="fixed bottom-4 right-4 space-y-2 z-50"></div><script> function showToast(message, type = "success") { const colors = { success: "bg-green-500 text-white", error: "bg-red-500 text-white", warning: "bg-yellow-400 text-black", info: "bg-blue-500 text-white" }; const toast = document.createElement("div"); toast.className = `px-4 py-2 rounded shadow-md ${colors[type]} animate-fade-in-out`; toast.textContent = message; document.getElementById("toast-container").appendChild(toast); setTimeout(() => { toast.remove(); }, 3000); // Toast disappears after 3 seconds } // Usage example showToast("Data saved successfully!", "success");</script><style> @keyframes fade-in-out { 0%, 100% { opacity: 0; transform: translateY(10px); } 10%, 90% { opacity: 1; transform: translateY(0); } } .animate-fade-in-out { animation: fade-in-out 3s forwards; }</style>
Tailwind Classes Used
Class | Purpose |
---|---|
bg-green-100 , bg-red-100 etc. | Background color based on alert type |
text-green-700 , text-red-700 | Text color based on alert type |
rounded-lg | Rounded corners |
fixed bottom-4 right-4 | Positioning for toasts |
shadow-md | Shadow for toast boxes |
animate-fade-in-out | Custom animation for toast fade |
Want me to create a more advanced toast notification system with buttons to dismiss, or integrate with React or Vue?