Bootstrap – Alerts
Bootstrap alerts are a feature of the Bootstrap framework that allows developers to display feedback messages to users. These alerts can indicate various states such as success, error, warning, or informational messages. Here’s a detailed explanation of the Alerts components in Bootstrap:
Basic Structure
An alert in Bootstrap is a simple div with the class .alert
and a contextual class to specify the type of alert:
<div class="alert alert-success" role="alert">
This is a success alert—check it out!
</div>
Contextual Classes
Bootstrap provides several contextual classes to represent different types of alerts:
.alert-primary
: Primary alert.alert-secondary
: Secondary alert.alert-success
: Success alert.alert-danger
: Danger alert (used for errors).alert-warning
: Warning alert.alert-info
: Informational alert.alert-light
: Light alert.alert-dark
: Dark alert
Example
<div class="alert alert-primary" role="alert">
This is a primary alert—check it out!
</div>
<div class="alert alert-secondary" role="alert">
This is a secondary alert—check it out!
</div>
<div class="alert alert-success" role="alert">
This is a success alert—check it out!
</div>
<div class="alert alert-danger" role="alert">
This is a danger alert—check it out!
</div>
<div class="alert alert-warning" role="alert">
This is a warning alert—check it out!
</div>
<div class="alert alert-info" role="alert">
This is an info alert—check it out!
</div>
<div class="alert alert-light" role="alert">
This is a light alert—check it out!
</div>
<div class="alert alert-dark" role="alert">
This is a dark alert—check it out!
</div>
Dismissible Alerts
Alerts can be made dismissible, meaning the user can close them. To create a dismissible alert, add the .alert-dismissible
class along with a close button inside the alert.
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
JavaScript for Dismissible Alerts
To make dismissible alerts work, include Bootstrap’s JavaScript and its dependencies:
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
Additional Customizations
- Icons: You can add icons to alerts for better visual representation.
- Links: Alerts can contain links styled with the
.alert-link
class.
<div class="alert alert-success" role="alert">
<strong>Well done!</strong> You successfully read this important alert message.
<a href="#" class="alert-link">Click here for more details.</a>
</div>