Bootstrap Alerts
Alerts show a message to the user, like a success, a warning or an error. They are made with the class .alert and a color class.
Alert colors
<div class="alert alert-primary" role="alert">A primary alert</div>
<div class="alert alert-success" role="alert">A success alert: the data is saved.</div>
<div class="alert alert-warning" role="alert">A warning alert: check your input.</div>
<div class="alert alert-danger" role="alert">A danger alert: something went wrong.</div>
<div class="alert alert-info" role="alert">An info alert</div>
Live preview
Always add role="alert", so screen readers read the message at once. Use the classes alert-secondary, alert-light and alert-dark for the other colors.
Links and extra content
<div class="alert alert-success" role="alert">
<h4 class="alert-heading">Well done!</h4>
<p>Your profile is updated. Read the <a href="#" class="alert-link">new terms</a> for more.</p>
<hr>
<p class="mb-0">Use <code>.alert-link</code> for links, so they match the color of the alert.</p>
</div>
Live preview
Dismissible alerts
Add .alert-dismissible, a close button with data-bs-dismiss="alert", and the classes fade show for a smooth effect.
<div class="alert alert-warning alert-dismissible fade show" role="alert" id="myAlert">
<strong>Holy guacamole!</strong> You should check some fields below.
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
Live preview
Let us click the close button in real Chrome and see what happens:
console.log('alert in the page before: ' + document.querySelectorAll('#myAlert').length);
document.querySelector('#myAlert .btn-close').click();
await new Promise(r => setTimeout(r, 600));
console.log('alert in the page after the click: ' + document.querySelectorAll('#myAlert').length);
Console output (real Chrome)
alert in the page before: 1
alert in the page after the click: 0
The alert is removed from the DOM after the fade effect. If you want to close it by code: bootstrap.Alert.getOrCreateInstance(element).close().
Alert with an icon
<div class="alert alert-info d-flex align-items-center" role="alert">
<i class="bi bi-info-circle-fill me-2"></i>
<div>An info alert with an icon.</div>
</div>
Live preview
The icon comes from Bootstrap Icons. See Bootstrap Icons.
Note:
Do not show too many alerts together. For a short message which disappears, use a toast. See Toasts. Next: Badges.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |