Bootstrap ยท Chapter 28 of 43

Bootstrap Toast

Toasts are small, non-blocking notification messages that appear briefly in a corner of the screen, similar to mobile app notifications. They are designed to be lightweight and easy to dismiss.

A toast has a .toast wrapper with a .toast-header and .toast-body, and it must be shown using Bootstrap's JavaScript Toast component since it is hidden by default.

Syntax
<div class="toast">
  <div class="toast-header">...</div>
  <div class="toast-body">Message</div>
</div>

Toast structure

The .toast-header often contains a small icon, title, timestamp, and close button, while .toast-body holds the main message text.

Showing a toast

Toasts are hidden by default and shown with JavaScript: create a new bootstrap.Toast(el) instance and call its .show() method, often triggered by a button click.

Example 1 (html)
<div class="toast" id="myToast" role="alert">
  <div class="toast-header">
    <strong class="me-auto">Notification</strong>
    <button class="btn-close" data-bs-dismiss="toast"></button>
  </div>
  <div class="toast-body">Your file has been uploaded successfully.</div>
</div>
<script>
  const toastEl = document.getElementById('myToast');
  const toast = new bootstrap.Toast(toastEl);
  toast.show();
</script>
Output
A small notification box appears with a title, close button, and a success message, then fades away automatically

The Toast JavaScript object controls showing and auto-hiding the notification.

Example 2 (html)
<div class="toast-container position-fixed bottom-0 end-0 p-3">
  <div class="toast show">
    <div class="toast-body">Saved!</div>
  </div>
</div>
Output
A small 'Saved!' toast fixed in the bottom-right corner of the screen

toast-container with position-fixed keeps notifications anchored to a corner of the viewport.

Key points

  • Toasts show brief, non-blocking notification messages.
  • They are hidden by default and require JavaScript to show.
  • .toast-header and .toast-body structure the notification content.
  • .toast-container with position utilities anchors toasts to a screen corner.
๐Ÿ’ก Note: By default, toasts auto-hide after a short delay, which can be customized with the data-bs-delay attribute.

๐Ÿ“ Quick Quiz

1. Are toasts visible by default?

2. Which class holds the main message of a toast?

3. Which attribute customizes how long a toast stays visible?