Dismissible alerts let users close messages they don't want to see anymore. This keeps the page clean and easy to use.
0
0
Dismissible alerts in Bootsrap
Introduction
Showing success messages after a form is submitted, letting users close them.
Displaying warnings or errors that users can dismiss when read.
Giving users temporary tips or notifications that can be removed.
Alerting users about updates or changes that don't need to stay visible.
Providing feedback that users can control by closing the alert box.
Syntax
Bootsrap
<div class="alert alert-warning alert-dismissible fade show" role="alert"> Your message here. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div>
The alert-dismissible class makes the alert closable.
The btn-close button triggers the closing action with data-bs-dismiss="alert".
Examples
A green success alert that can be dismissed by the user.
Bootsrap
<div class="alert alert-success alert-dismissible fade show" role="alert"> Success! Your action worked. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div>
A red error alert with a close button.
Bootsrap
<div class="alert alert-danger alert-dismissible fade show" role="alert"> Error! Something went wrong. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div>
A blue info alert that users can close.
Bootsrap
<div class="alert alert-info alert-dismissible fade show" role="alert"> Info: Remember to save your work. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div>
Sample Program
This page shows a yellow warning alert with a close button. When you click the close button, the alert disappears smoothly.
Bootsrap
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Dismissible Alert Example</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <main class="container mt-5"> <h1>Dismissible Alert Demo</h1> <div class="alert alert-warning alert-dismissible fade show" role="alert"> <strong>Warning!</strong> Please check your input. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> </main> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> </body> </html>
OutputSuccess
Important Notes
Make sure to include Bootstrap's JavaScript bundle for the dismiss feature to work.
The fade show classes add a smooth fade-out effect when closing.
Use aria-label="Close" on the button for screen reader accessibility.
Summary
Dismissible alerts let users close messages to keep the page tidy.
Use alert-dismissible and a btn-close button with data-bs-dismiss="alert".
Always include Bootstrap's JS for the close button to work properly.