BS5 Alerts
Bootstrap 5 provides a flexible and customizable way to display contextual feedback messages using alerts. Alerts are lightweight, easy to style, and come with predefined classes for different use cases.
Key Topics
Basic Alerts
Bootstrap alerts use the .alert
class along with contextual color classes like .alert-primary
, .alert-danger
, etc., to convey different types of messages.
<div class="alert alert-primary" role="alert">
This is a primary alert!</div>
<div class="alert alert-danger" role="alert">
This is a danger alert!</div>
Explanation: The role="alert"
attribute ensures accessibility, and the contextual classes apply different colors to the alerts.
Dismissible Alerts
Make alerts dismissible by adding the .alert-dismissible
class and a close button.
<div class="alert alert-warning alert-dismissible fade show" role="alert">
This is a dismissible warning alert!<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
Explanation: The .btn-close
class adds a close button, and data-bs-dismiss="alert"
handles the dismissal logic.
Styled Alerts
Alerts can be styled further with additional classes or custom CSS to match your design needs.
<div class="alert alert-success text-center fw-bold" role="alert">
Centered success alert with bold text!</div>
Explanation: Combining utility classes like .text-center
and .fw-bold
gives additional flexibility for custom styling.
Complete Alert Example
Below is a complete HTML page demonstrating various Bootstrap alert styles and features.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap 5 Alerts Demo</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container my-4">
<h2>Bootstrap Alerts</h2>
<div class="alert alert-primary" role="alert">
Primary alert!</div>
<div class="alert alert-success alert-dismissible fade show" role="alert">
Success alert with dismissible feature!<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<div class="alert alert-warning text-center" role="alert">
Centered warning alert!</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Explanation: This page demonstrates the use of basic, dismissible, and styled alerts in a responsive layout.
Key Takeaways
- Bootstrap alerts provide a simple way to display contextual feedback.
- Use
.alert-dismissible
and.btn-close
for interactive alerts. - Combine utility classes for custom alert styling.