Salta al contenuto principale Passa alla navigazione dei documenti
Check
in English

Brindisi

Notifiche push ai tuoi visitatori con un brindisi, un messaggio di avviso leggero e facilmente personalizzabile.

I brindisi sono notifiche leggere progettate per imitare le notifiche push che sono state rese popolari dai sistemi operativi mobili e desktop. Sono costruiti con flexbox, quindi sono facili da allineare e posizionare.

Panoramica

Cose da sapere quando si utilizza il plug-in toast:

  • I brindisi sono attivati ​​per motivi di prestazioni, quindi devi inizializzarli tu stesso .
  • I brindisi si nasconderanno automaticamente se non specifichi autohide: false.
L'effetto di animazione di questo componente dipende dalla prefers-reduced-motionmedia query. Vedi la sezione movimento ridotto della nostra documentazione sull'accessibilità .

Esempi

Di base

Per incoraggiare brindisi estensibili e prevedibili, consigliamo un'intestazione e un corpo. Le intestazioni Toast utilizzano display: flex, consentendo un facile allineamento dei contenuti grazie alle nostre utility margin e flexbox.

I brindisi sono flessibili quanto ti serve e hanno pochissimo markup richiesto. Come minimo, abbiamo bisogno di un singolo elemento per contenere i tuoi contenuti "tostati" e incoraggiare fortemente un pulsante di eliminazione.

html
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-header">
    <img src="..." class="rounded me-2" alt="...">
    <strong class="me-auto">Bootstrap</strong>
    <small>11 mins ago</small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>
In precedenza, i nostri script aggiungevano dinamicamente la .hideclasse per nascondere completamente un brindisi (con display:none, anziché solo con opacity:0). Questo ora non è più necessario. Tuttavia, per compatibilità con le versioni precedenti, il nostro script continuerà a alternare la classe (anche se non ce n'è bisogno pratico) fino alla prossima versione principale.

Esempio dal vivo

Fai clic sul pulsante in basso per mostrare un brindisi (posizionato con le nostre utilità nell'angolo in basso a destra) che è stato nascosto per impostazione predefinita.

<button type="button" class="btn btn-primary" id="liveToastBtn">Show live toast</button>

<div class="toast-container position-fixed bottom-0 end-0 p-3">
  <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small>11 mins ago</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
  </div>
</div>

Usiamo il seguente JavaScript per attivare la nostra demo di brindisi dal vivo:

const toastTrigger = document.getElementById('liveToastBtn')
const toastLiveExample = document.getElementById('liveToast')
if (toastTrigger) {
  toastTrigger.addEventListener('click', () => {
    const toast = new bootstrap.Toast(toastLiveExample)

    toast.show()
  })
}

Traslucido

I toast sono leggermente traslucidi per fondersi con ciò che c'è sotto di loro.

html
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-header">
    <img src="..." class="rounded me-2" alt="...">
    <strong class="me-auto">Bootstrap</strong>
    <small class="text-muted">11 mins ago</small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>

Impilamento

Puoi impilare i toast avvolgendoli in un contenitore per toast, che aggiungerà una certa spaziatura verticalmente.

html
<div class="toast-container position-static">
  <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small class="text-muted">just now</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      See? Just like this.
    </div>
  </div>

  <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small class="text-muted">2 seconds ago</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      Heads up, toasts will stack automatically
    </div>
  </div>
</div>

Contenuti personalizzati

Personalizza i tuoi brindisi rimuovendo i sottocomponenti, modificandoli con le utilità o aggiungendo il tuo markup. Qui abbiamo creato un brindisi più semplice rimuovendo l'impostazione predefinita .toast-header, aggiungendo un'icona Nascondi personalizzata da Bootstrap Icons e utilizzando alcune utilità flexbox per regolare il layout.

html
<div class="toast align-items-center" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="d-flex">
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
    <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
</div>

In alternativa, puoi anche aggiungere ulteriori controlli e componenti ai brindisi.

html
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-body">
    Hello, world! This is a toast message.
    <div class="mt-2 pt-2 border-top">
      <button type="button" class="btn btn-primary btn-sm">Take action</button>
      <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="toast">Close</button>
    </div>
  </div>
</div>

Combinazioni di colori

Basandosi sull'esempio sopra, puoi creare diverse combinazioni di colori di toast con le nostre utilità di colore e sfondo . Qui abbiamo aggiunto .text-bg-primaryal .toast, e poi aggiunto .btn-close-whiteal nostro pulsante di chiusura. Per un bordo nitido, rimuoviamo il bordo predefinito con .border-0.

html
<div class="toast align-items-center text-bg-primary border-0" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="d-flex">
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
</div>

Posizionamento

Posiziona i brindisi con CSS personalizzati quando ne hai bisogno. L'angolo in alto a destra viene spesso utilizzato per le notifiche, così come l'angolo in alto al centro. Se intendi mostrare solo un brindisi alla volta, metti gli stili di posizionamento direttamente sul .toast.

Bootstrap 11 minuti fa
Ciao mondo! Questo è un messaggio di brindisi.
html
<form>
  <div class="mb-3">
    <label for="selectToastPlacement">Toast placement</label>
    <select class="form-select mt-2" id="selectToastPlacement">
      <option value="" selected>Select a position...</option>
      <option value="top-0 start-0">Top left</option>
      <option value="top-0 start-50 translate-middle-x">Top center</option>
      <option value="top-0 end-0">Top right</option>
      <option value="top-50 start-0 translate-middle-y">Middle left</option>
      <option value="top-50 start-50 translate-middle">Middle center</option>
      <option value="top-50 end-0 translate-middle-y">Middle right</option>
      <option value="bottom-0 start-0">Bottom left</option>
      <option value="bottom-0 start-50 translate-middle-x">Bottom center</option>
      <option value="bottom-0 end-0">Bottom right</option>
    </select>
  </div>
</form>
<div aria-live="polite" aria-atomic="true" class="bg-dark position-relative bd-example-toasts">
  <div class="toast-container p-3" id="toastPlacement">
    <div class="toast">
      <div class="toast-header">
        <img src="..." class="rounded me-2" alt="...">
        <strong class="me-auto">Bootstrap</strong>
        <small>11 mins ago</small>
      </div>
      <div class="toast-body">
        Hello, world! This is a toast message.
      </div>
    </div>
  </div>
</div>

Per i sistemi che generano più notifiche, prendi in considerazione l'utilizzo di un elemento di wrapping in modo che possano essere facilmente impilati.

html
<div aria-live="polite" aria-atomic="true" class="position-relative">
  <!-- Position it: -->
  <!-- - `.toast-container` for spacing between toasts -->
  <!-- - `top-0` & `end-0` to position the toasts in the upper right corner -->
  <!-- - `.p-3` to prevent the toasts from sticking to the edge of the container  -->
  <div class="toast-container top-0 end-0 p-3">

    <!-- Then put toasts within -->
    <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="toast-header">
        <img src="..." class="rounded me-2" alt="...">
        <strong class="me-auto">Bootstrap</strong>
        <small class="text-muted">just now</small>
        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
      <div class="toast-body">
        See? Just like this.
      </div>
    </div>

    <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="toast-header">
        <img src="..." class="rounded me-2" alt="...">
        <strong class="me-auto">Bootstrap</strong>
        <small class="text-muted">2 seconds ago</small>
        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
      <div class="toast-body">
        Heads up, toasts will stack automatically
      </div>
    </div>
  </div>
</div>

Puoi anche divertirti con le utility flexbox per allineare i toast orizzontalmente e/o verticalmente.

html
<!-- Flexbox container for aligning the toasts -->
<div aria-live="polite" aria-atomic="true" class="d-flex justify-content-center align-items-center w-100">

  <!-- Then put toasts within -->
  <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small>11 mins ago</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
  </div>
</div>

Accessibilità

Toasts are intended to be small interruptions to your visitors or users, so to help those with screen readers and similar assistive technologies, you should wrap your toasts in an aria-live region. Changes to live regions (such as injecting/updating a toast component) are automatically announced by screen readers without needing to move the user’s focus or otherwise interrupt the user. Additionally, include aria-atomic="true" to ensure that the entire toast is always announced as a single (atomic) unit, rather than just announcing what was changed (which could lead to problems if you only update part of the toast’s content, or if displaying the same toast content at a later point in time). If the information needed is important for the process, e.g. for a list of errors in a form, then use the alert component instead of toast.

Note that the live region needs to be present in the markup before the toast is generated or updated. If you dynamically generate both at the same time and inject them into the page, they will generally not be announced by assistive technologies.

You also need to adapt the role and aria-live level depending on the content. If it’s an important message like an error, use role="alert" aria-live="assertive", otherwise use role="status" aria-live="polite" attributes.

As the content you’re displaying changes, be sure to update the delay timeout so that users have enough time to read the toast.

<div class="toast" role="alert" aria-live="polite" aria-atomic="true" data-bs-delay="10000">
  <div role="alert" aria-live="assertive" aria-atomic="true">...</div>
</div>

When using autohide: false, you must add a close button to allow users to dismiss the toast.

html
<div role="alert" aria-live="assertive" aria-atomic="true" class="toast" data-bs-autohide="false">
  <div class="toast-header">
    <img src="..." class="rounded me-2" alt="...">
    <strong class="me-auto">Bootstrap</strong>
    <small>11 mins ago</small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>

While technically it’s possible to add focusable/actionable controls (such as additional buttons or links) in your toast, you should avoid doing this for autohiding toasts. Even if you give the toast a long delay timeout, keyboard and assistive technology users may find it difficult to reach the toast in time to take action (since toasts don’t receive focus when they are displayed). If you absolutely must have further controls, we recommend using a toast with autohide: false.

CSS

Variables

Added in v5.2.0

As part of Bootstrap’s evolving CSS variables approach, toasts now use local CSS variables on .toast for enhanced real-time customization. Values for the CSS variables are set via Sass, so Sass customization is still supported, too.

  --#{$prefix}toast-zindex: #{$zindex-toast};
  --#{$prefix}toast-padding-x: #{$toast-padding-x};
  --#{$prefix}toast-padding-y: #{$toast-padding-y};
  --#{$prefix}toast-spacing: #{$toast-spacing};
  --#{$prefix}toast-max-width: #{$toast-max-width};
  @include rfs($toast-font-size, --#{$prefix}toast-font-size);
  --#{$prefix}toast-color: #{$toast-color};
  --#{$prefix}toast-bg: #{$toast-background-color};
  --#{$prefix}toast-border-width: #{$toast-border-width};
  --#{$prefix}toast-border-color: #{$toast-border-color};
  --#{$prefix}toast-border-radius: #{$toast-border-radius};
  --#{$prefix}toast-box-shadow: #{$toast-box-shadow};
  --#{$prefix}toast-header-color: #{$toast-header-color};
  --#{$prefix}toast-header-bg: #{$toast-header-background-color};
  --#{$prefix}toast-header-border-color: #{$toast-header-border-color};
  

Sass variables

$toast-max-width:                   350px;
$toast-padding-x:                   .75rem;
$toast-padding-y:                   .5rem;
$toast-font-size:                   .875rem;
$toast-color:                       null;
$toast-background-color:            rgba($white, .85);
$toast-border-width:                $border-width;
$toast-border-color:                var(--#{$prefix}border-color-translucent);
$toast-border-radius:               $border-radius;
$toast-box-shadow:                  $box-shadow;
$toast-spacing:                     $container-padding-x;

$toast-header-color:                $gray-600;
$toast-header-background-color:     rgba($white, .85);
$toast-header-border-color:         rgba($black, .05);

Usage

Initialize toasts via JavaScript:

const toastElList = document.querySelectorAll('.toast')
const toastList = [...toastElList].map(toastEl => new bootstrap.Toast(toastEl, option))

Triggers

Dismissal can be achieved with the data attribute on a button within the toast as demonstrated below:

<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>

or on a button outside the toast using the data-bs-target as demonstrated below:

<button type="button" class="btn-close" data-bs-dismiss="toast" data-bs-target="#my-toast" aria-label="Close"></button>

Options

As options can be passed via data attributes or JavaScript, you can append an option name to data-bs-, as in data-bs-animation="{value}". Make sure to change the case type of the option name from “camelCase” to “kebab-case” when passing the options via data attributes. For example, use data-bs-custom-class="beautifier" instead of data-bs-customClass="beautifier".

As of Bootstrap 5.2.0, all components support an experimental reserved data attribute data-bs-config that can house simple component configuration as a JSON string. When an element has data-bs-config='{"delay":0, "title":123}' and data-bs-title="456" attributes, the final title value will be 456 and the separate data attributes will override values given on data-bs-config. In addition, existing data attributes are able to house JSON values like data-bs-delay='{"show":0,"hide":150}'.

Name Type Default Description
animation boolean true Apply a CSS fade transition to the toast.
autohide boolean true Automatically hide the toast after the delay.
delay number 5000 Delay in milliseconds before hiding the toast.

Methods

Asynchronous methods and transitions

All API methods are asynchronous and start a transition. They return to the caller as soon as the transition is started but before it ends. In addition, a method call on a transitioning component will be ignored.

See our JavaScript documentation for more information.

Method Description
dispose Hides an element’s toast. Your toast will remain on the DOM but won’t show anymore.
getInstance Static method which allows you to get the toast instance associated with a DOM element.
For example: const myToastEl = document.getElementById('myToastEl') const myToast = bootstrap.Toast.getInstance(myToastEl) Returns a Bootstrap toast instance.
getOrCreateInstance Static method which allows you to get the toast instance associated with a DOM element, or create a new one, in case it wasn’t initialized.
const myToastEl = document.getElementById('myToastEl') const myToast = bootstrap.Toast.getOrCreateInstance(myToastEl) Returns a Bootstrap toast instance.
hide Hides an element’s toast. Returns to the caller before the toast has actually been hidden (i.e. before the hidden.bs.toast event occurs). You have to manually call this method if you made autohide to false.
isShown Returns a boolean according to toast’s visibility state.
show Reveals an element’s toast. Returns to the caller before the toast has actually been shown (i.e. before the shown.bs.toast event occurs). You have to manually call this method, instead your toast won’t show.

Events

Event Description
hide.bs.toast Questo evento viene generato immediatamente quando hideviene chiamato il metodo dell'istanza.
hidden.bs.toast Questo evento viene generato quando il brindisi ha finito di essere nascosto all'utente.
show.bs.toast Questo evento viene attivato immediatamente quando showviene chiamato il metodo dell'istanza.
shown.bs.toast Questo evento viene attivato quando il brindisi è stato reso visibile all'utente.
const myToastEl = document.getElementById('myToast')
myToastEl.addEventListener('hidden.bs.toast', () => {
  // do something...
})