Part of our complete guide: CSS Snippets →
UI Component · HTML + CSS + JS
Toast Notifications
Four toast variants — success, error, warning, info. Slide in from the right, auto-dismiss with a progress bar, and stack gracefully.
Last updated: October 2026 · 8 min read
A toast notification is a small, auto-dismissing message that confirms an action. It appears in a corner, doesn't block interaction, and disappears after 3–5 seconds. Use role="status" for success/info, role="alert" for errors.
What you get: Complete toast system with 4 variants (success, error, warning, info), slide-in animation, progress bar showing time until dismiss, pause-on-hover, stacking, and manual close. Fully accessible.
Why toasts replace alerts
The native alert() dialog is the worst UI pattern on the web. It blocks everything. It interrupts whatever the user was doing. It looks the same whether the news is good or bad. It requires a click to dismiss — even for a message the user doesn't care about. Every time a developer uses alert(), a user has a slightly worse day.
Toasts replace them without losing the notification. A success message slides in from the bottom-right, sits for 3 seconds, slides out. The user sees it, understands it, and never interrupts their workflow. Errors stay longer and require manual dismissal because they're important. Warnings pause when hovered so users can read them at their own pace.
The pattern below is the modern standard. Four variants with clear visual identity. A progress bar that shows exactly how long until dismiss — so users know they can hover to pause. Stacking means multiple toasts can appear without overlapping. And everything is accessible: live regions for screen readers, keyboard-accessible close buttons, and no reliance on color alone.
🎬 Live Demo
Click each button to trigger a toast. Hover over a toast to pause its timer.
🎬 Try It
Click any button. The toast appears in the bottom-right (bottom-center on mobile).
Complete code
<!-- Toast container (add once in your HTML) -->
<div class="toast-container" id="toastContainer"></div>
<style>
.toast-container {
position: fixed;
bottom: 5.5rem; right: 1rem;
display: flex;
flex-direction: column-reverse;
gap: 0.75rem;
z-index: 9999;
pointer-events: none;
max-width: 380px;
width: calc(100% - 2rem);
}
.toast {
display: flex; align-items: flex-start;
gap: 0.75rem;
background: #1e293b;
border: 1px solid #334155;
border-left-width: 4px;
border-radius: 0.75rem;
padding: 0.9rem 1rem;
box-shadow: 0 10px 30px rgba(0,0,0,0.4);
pointer-events: auto;
animation: toastSlideIn 0.35s cubic-bezier(0.16, 1, 0.3, 1);
position: relative; overflow: hidden;
}
.toast.removing {
animation: toastSlideOut 0.25s ease forwards;
}
@keyframes toastSlideIn {
from { opacity: 0; transform: translateX(120%); }
to { opacity: 1; transform: translateX(0); }
}
@keyframes toastSlideOut {
from { opacity: 1; transform: translateX(0); }
to { opacity: 0; transform: translateX(120%); }
}
.toast.success { border-left-color: #16a34a; }
.toast.error { border-left-color: #dc2626; }
.toast.warning { border-left-color: #d97706; }
.toast.info { border-left-color: #3b82f6; }
.toast-icon {
flex-shrink: 0;
width: 22px; height: 22px;
border-radius: 50%;
display: flex; align-items: center; justify-content: center;
font-size: 0.75rem; color: #fff; font-weight: 700;
}
.toast.success .toast-icon { background: #16a34a; }
.toast.error .toast-icon { background: #dc2626; }
.toast.warning .toast-icon { background: #d97706; }
.toast.info .toast-icon { background: #3b82f6; }
.toast-body { flex: 1; min-width: 0; }
.toast-title { color: #fff; font-weight: 700; font-size: 0.85rem; margin-bottom: 0.15rem; }
.toast-message { color: #cbd5e1; font-size: 0.78rem; line-height: 1.4; }
.toast-close {
flex-shrink: 0;
background: transparent; border: none;
color: #64748b; cursor: pointer;
font-size: 1rem; padding: 0;
width: 22px; height: 22px;
display: flex; align-items: center; justify-content: center;
border-radius: 0.375rem;
transition: all 0.15s;
}
.toast-close:hover { background: #334155; color: #fff; }
.toast-progress {
position: absolute; bottom: 0; left: 0;
height: 2px; background: rgba(255, 255, 255, 0.4);
transform-origin: left;
animation: progress linear forwards;
}
.toast.success .toast-progress { background: #22c55e; }
.toast.error .toast-progress { background: #ef4444; }
.toast.warning .toast-progress { background: #f59e0b; }
.toast.info .toast-progress { background: #60a5fa; }
@keyframes progress {
from { transform: scaleX(1); }
to { transform: scaleX(0); }
}
.toast:hover .toast-progress { animation-play-state: paused; }
@media (max-width: 640px) {
.toast-container {
bottom: 5rem;
right: 0.75rem; left: 0.75rem;
max-width: none;
}
}
</style>
<script>
const container = document.getElementById('toastContainer');
const icons = {
success: '✓',
error: '✕',
warning: '!',
info: 'i'
};
function showToast(type, title, message, duration = 4000) {
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.setAttribute('role', type === 'error' ? 'alert' : 'status');
toast.innerHTML = `
<div class="toast-icon">${icons[type]}</div>
<div class="toast-body">
<div class="toast-title">${title}</div>
<div class="toast-message">${message}</div>
</div>
<button class="toast-close" aria-label="Close">✕</button>
<div class="toast-progress" style="animation-duration: ${duration}ms;"></div>
`;
container.appendChild(toast);
const remove = () => {
toast.classList.add('removing');
setTimeout(() => toast.remove(), 250);
};
toast.querySelector('.toast-close').addEventListener('click', remove);
// Errors don't auto-dismiss
if (type !== 'error') {
const timer = setTimeout(remove, duration);
// Pause on hover
toast.addEventListener('mouseenter', () => clearTimeout(timer));
toast.addEventListener('mouseleave', () => {
setTimeout(remove, 1500);
});
}
}
</script>
How toast notifications work
All toasts share one .toast-container fixed to the bottom-right. New toasts are appended to it, stacked with flex-direction: column-reverse. The container is pointer-events: none so it doesn't block clicks on the page below — each toast re-enables clicks on itself with pointer-events: auto.
The toast starts at translateX(120%) (off-screen right) and animates to translateX(0). Slide-out reverses it. Only transform and opacity are animated — both are GPU-accelerated, so animation stays smooth even when the main thread is busy.
Each toast has a thin progress bar at the bottom. It's animated from scaleX(1) to scaleX(0) over the toast's duration. This tells users exactly how long they have before it disappears — which is why they know they can hover to pause if they need more time.
On mouseenter, the timeout is cleared (pause). On mouseleave, a fresh short timeout (1.5s) is set so users can't accidentally hover and trap it forever. The CSS animation for the progress bar also pauses via animation-play-state: paused, so the visual stays in sync with the actual timeout.
Success, warning, and info toasts auto-dismiss. Errors don't — because errors usually mean the user needs to do something (fix a validation issue, retry a request). Auto-dismissing an error before it's read is a UX failure. The user has to click X or fix the issue themselves.
Every toast gets role="status" (or role="alert" for errors). Screen readers announce the toast content automatically. Without this, blind users never know a toast appeared — they'd navigate the page wondering why nothing happened when they clicked "Save".
🔬 Edge cases
The problems that break toast notifications in production.
If a loop fires 20 toasts, the stack overflows the screen. Fix: cap the number of simultaneous toasts (3–4 max). When a new one arrives over the cap, remove the oldest. Users see the most recent, most relevant messages.
Users can't close a toast they've already read. Worse, if the auto-dismiss timer is broken (network lag, timer bugs), the toast sticks forever. Fix: always include a close button, even on auto-dismiss toasts.
On mobile, the toast container overlaps the fixed bottom navbar. Users can't see the message. Fix: bottom: 5.5rem instead of bottom: 1rem — leaves room for the navbar. Same for desktop if there's a fixed footer.
A toast fires while a modal is open, but it renders behind the modal overlay. Fix: use a very high z-index (9999+). Or place the toast container inside the modal's DOM when it's open (rare — usually z-index is enough).
The toast appears visually but blind users don't hear it. Fix: role="status" on success/info, role="alert" on error/warning. Also test with VoiceOver/NVDA — the entire pattern falls apart without this.
The user sees "Error" for 3 seconds and it disappears before they can read the details. Fix: never auto-dismiss errors. Let them require manual close. Success messages can auto-dismiss; errors cannot.
Users move their mouse toward a toast to read it, but the timer continues and the toast disappears. Fix: mouseenter clears the timer, mouseleave restarts it. The progress bar pauses too. This is a small detail but users notice.
Red vs green is invisible to color-blind users (8% of men). Fix: pair color with an icon (✓ ✕ ! i) and text labels. This is a WCAG requirement — color must never be the only differentiator.
♿ Accessibility
Toasts are one of the most commonly broken components for screen readers. Here's what makes them work.
| Requirement | Implementation | Why |
|---|---|---|
| Live region | role="status" / role="alert" | Screen readers announce automatically |
| Polite vs assertive | status for success/info | Doesn't interrupt current task |
| Close button label | aria-label="Close" | Screen reader identifies purpose |
| No color-only | Icon + text label | Color-blind users understand |
| Pause on focus | :focus-within | Keyboard users can dismiss |
The critical detail: role="alert" interrupts the screen reader's current utterance. role="status" waits. For success messages, waiting is polite. For errors, interrupting is appropriate — the user needs to know immediately. Getting this wrong makes the component either annoying or useless.
⚡ Performance
| Aspect | Value | Notes |
|---|---|---|
| CSS size | ~2KB | No framework, no dependencies |
| JS size | ~40 lines | Vanilla, no library |
| Animation | transform + opacity | GPU-accelerated, 60fps |
| DOM nodes | ~5 per toast | Removed cleanly on dismiss |
Cleanup matters more than speed. Toasts that aren't removed from the DOM accumulate silently. After 50 toasts, the DOM has 250 extra nodes — slow, buggy, and eventually visible. The remove() call after the slide-out animation is what prevents this. Never forget it.
⚠️ Common mistakes
- No
role="status"orrole="alert". Screen readers never announce the toast. Fails WCAG 2.1 AA. - Auto-dismissing errors. User misses the message, doesn't know what went wrong, tries again, fails again.
- No limit on stacking. 10 toasts pile up and obscure the whole screen.
- Not removing toasts from the DOM. Memory leak — DOM grows forever.
- Animating
widthormargin. Layout thrashing. Usetransform: translateX()andopacity. - Overlapping the fixed bottom navbar. Toasts appear behind the mobile navbar, invisible.
- Color-only indication. Red vs green fails for 8% of men. Add icons and text.
- No pause on hover. User reaches for the toast, it disappears. Small thing, feels broken.
❓ Frequently asked questions
What is a toast notification?
A toast is a small, temporary message that appears on screen to inform users of an action's result. It auto-dismisses after a few seconds and usually appears in a corner of the viewport. Unlike a modal, it doesn't block interaction.
How do I create a toast notification in HTML?
Create a container div fixed to a corner of the viewport. Inside, add toast elements with role='status' or role='alert'. Show and hide them by toggling a class. Auto-dismiss with setTimeout. Slide in with CSS transitions.
What is the difference between role=status and role=alert?
role='status' is a polite live region — screen readers announce it after finishing their current utterance. role='alert' is assertive — it interrupts. Use status for success/info, alert for errors and warnings.
How long should a toast stay visible?
3–5 seconds for success and info. 5–7 seconds for warnings. Never auto-dismiss errors — let users read and dismiss them manually. Also pause the timer on hover/focus so users can finish reading.
Should toasts stack?
Yes, but limit it. Show a maximum of 3–4 toasts at once. Add newer ones above or below older ones (be consistent). Older toasts push out when the limit is reached. Use flexbox with gap for smooth stacking.
What's the best position for toast notifications?
Bottom-right for desktop, bottom-center for mobile. Top-right is also common but can clash with sticky navbars. The bottom is generally safer because it's less likely to overlap critical UI.
How do I make toasts accessible?
Use role='status' or role='alert' for screen reader announcements. Include a close button with aria-label. Never use color alone to convey meaning — pair it with an icon and text. Pause auto-dismiss on hover/focus.
Should toast notifications be dismissible?
Yes, always. Some users read slowly, some want to review what happened. Add an X button on every toast. For critical errors, disable auto-dismiss entirely and require manual dismissal.