Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to make a toast notification

Short answer

A toast is a block in the corner of the screen with position: fixed. With the popover attribute a button shows it without a script:

<style>
  .toast { inset: auto 16px 16px auto; margin: 0; padding: 12px 16px; border: none; border-radius: 8px; background: #222; color: white; box-shadow: 0 6px 20px rgb(0 0 0 / 30%); }
</style>
 
<button popovertarget="saved">Save</button>
<div id="saved" class="toast" popover>Changes saved ✓</div>

A popover already has position: fixed and sits in the center. inset: auto 16px 16px auto moves it to the bottom-right corner. A click anywhere closes the notice.

Showing up and hiding itself

@starting-style lets the toast slide in smoothly, and one line of script hides it after a couple of seconds:

<style>
  .t { inset: auto 16px 16px auto; margin: 0; padding: 12px 16px; border: none; border-radius: 8px; background: seagreen; color: white; transition: translate 0.3s; }
  @starting-style { .t:popover-open { translate: 0 20px; } }
</style>
 
<button popovertarget="added" onclick="setTimeout(() => added.hidePopover(), 2500)">Add to cart</button>
<div id="added" class="t" popover="manual">Added to cart</div>

A popover="manual" does not close on an outside click — only the script or a button closes it.

For screen readers

To have the notice read aloud, keep an empty container with role="status" on the page and insert the text into it.

Common mistake

Showing errors and important actions like "Undo delete" in a toast that disappears by itself. People may not have time to read or click. Show errors next to the field, and keep action toasts open until closed by hand.

Functions used in this recipe

  • popover — Turns an element into a layer that pops up over the page — without JavaScript.
  • position — How an element is positioned: in the normal flow or by offsets.
  • animation — Runs a `@keyframes` animation on an element.

Thanks for reading!

Donate to the site — we work hard for you.