Bootstrap Alerts

You will discover in this article how to use Bootstrap to generate alert messages.


Creating Alert Messages with Bootstrap

Alert boxes are frequently used to draw attention to important information that requires immediate notice from end users, such as warning, error, or confirmation messages.

With Bootstrap, you can easily create stylish alert messages for various purposes by applying contextual classes (e.g., .alert-success, .alert-warning, .alert-info, etc.) to the .alert base class. Additionally, you have the option to include an optional close button to dismiss any alert.

Bootstrap offers a total of 8 different types of alerts. The most commonly used ones include success, error or danger, warning, and info alerts.

<!-- Success Alert -->
    <div class="alert alert-success alert-dismissible fade show">
        <strong>Success!</strong> Your message has been sent successfully.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    <!-- Error Alert -->
    <div class="alert alert-danger alert-dismissible fade show">
        <strong>Error!</strong> A problem has been occurred while submitting your data.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    <!-- Warning Alert -->
    <div class="alert alert-warning alert-dismissible fade show">
        <strong>Warning!</strong> There was a problem with your network connection.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    <!-- Info Alert -->
    <div class="alert alert-info alert-dismissible fade show">
        <strong>Info!</strong> Please read the comments carefully.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

Here are the final four Bootstrap notifications, each of which has a variety of uses.

<!-- Primary Alert -->
    <div class="alert alert-primary alert-dismissible fade show">
        <strong>Primary!</strong>A simple primary alert box.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    <!-- Secondary Alert -->
    <div class="alert alert-secondary alert-dismissible fade show">
        <strong>Secondary!</strong>A simple secondary alert box.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    <!-- Dark Alert -->
    <div class="alert alert-dark alert-dismissible fade show">
        <strong>Dark!</strong>A simple dark alert box.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    <!-- Light Alert -->
    <div class="alert alert-light alert-dismissible fade show">
        <strong>Light!</strong>A simple light alert box.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    

Tip: To enable a fading transition effect while closing the alert boxes, you can use the .fade and .show classes on the .alert element. If animation is not desired, these classes can be omitted. Proper positioning of the close button .btn-close requires the .alert-dismissible class on the .alert element. If your alert doesn't have a close button, this class can be skipped.


Adding Icons to Bootstrap Alerts

Bootstrap alerts can also contain icons. You can use either Bootstrap icons or third-party icons like Font Awesome. Here's an example to demonstrate this feature.

  <!-- Success Alert -->
    <div class="alert alert-success alert-dismissible d-flex align-items-center fade show">
      	<i class="bi-check-circle-fill"></i>
        <strong class="mx-2">Success!</strong> Your message has been sent successfully. 
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    <!-- Error Alert -->
    <div class="alert alert-danger alert-dismissible d-flex align-items-center fade show">
      	<i class="bi-exclamation-octagon-fill"></i>
        <strong class="mx-2">Error!</strong> A problem has been occurred while submitting your data.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    <!-- Warning Alert -->
    <div class="alert alert-warning alert-dismissible d-flex align-items-center fade show">
      	<i class="bi-exclamation-triangle-fill"></i>
        <strong class="mx-2">Warning!</strong> There was a problem with your network connection.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

Additional Content inside Alerts

Moreover, you can include additional HTML elements such as headings, paragraphs, and dividers inside an alert. To manage spacing between the elements, margin utility classes can be utilized.

<div class="alert alert-danger alert-dismissible fade show">
        <h4 class="alert-heading"><i class="bi-exclamation-octagon-fill"></i> Oops! Something went wrong.</h4>
        <p>Before moving further, all mandatory fields must be filled out with a valid value. Put your mouse over the info symbol next to the form's field if you need assistance.</p>
        <hr>
        <p class="mb-0">When you have finished filling out all the details, click "Next" to move forward.</p>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

Matching Links Color inside Alerts

To quickly create colored links that match the alert's style, you can apply the utility class .alert-link to the links inside the alert, as shown in the example below:

<div class="alert alert-warning alert-dismissible fade show">
    <strong>Warning!</strong> A simple warning alert with <a href="#" class="alert-link">an example link</a>.
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>

You may do the same for links within other alerts boxes. Let's attempt the next illustration:

 <!-- Success Alert -->
    <div class="alert alert-success alert-dismissible fade show">
        <strong>Success!</strong> Success alert with <a href="#" class="alert-link">an example link</a>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    <!-- Error Alert -->
    <div class="alert alert-danger alert-dismissible fade show">
        <strong>Error!</strong> Danger alert with <a href="#" class="alert-link">an example link</a>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

Closing Alerts via Data Attribute

Data attributes provide a simple way to add close functionality to alert boxes.

By adding the data-bs-dismiss=alert attribute to the close button, the containing alert message box is automatically dismissed. Additionally, the .alert-dismissible class is needed for proper positioning of the .btn-close button.

<div class="alert alert-info alert-dismissible fade show">
    <strong>Note!</strong> A simple example of dismissible alert.
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>

Closing Alerts via JavaScript

Alternatively, you can also dismiss an alert via JavaScript using Bootstrap's provided methods.

<script>
$(document).ready(function () {
    $("#myBtn").click(function () {
        $("#myAlert").alert("close");
    });
});
</script>

Bootstrap Alert Methods

These are the standard Bootstrap's alerts methods:

close

This method closes an alert by removing it from the DOM. If the .fade and .show classes are present on the element, the alert will fade out before being removed.

<script>
$(document).ready(function () {
    $("#myBtn").click(function () {
        $("#myAlert").alert("close");
    });
});
</script>

Bootstrap Alert Events

The alert classes in Bootstrap has a limited number of events for hooking into alerts functionalities.

  • close.bs.alert: When the instance's method close is invoked, this event is instantly triggered.
  • closed.bs.alert: When alerts has been closed and all CSS transitions are complete, this event is fired.

Lastly, the following example displays an alert message to the user when the fade-out transition of an alert message box has been fully completed.

<script>
                    $(document).ready(function () {
                        $("#myAlert").on("closed.bs.alert", function () {
                            alert("Alert message box has been closed.");
                        });
                    });
</script>

FAQ

What is a Bootstrap Alert?

A Bootstrap Alert is a UI component provided by the Bootstrap framework, which is a popular front-end development framework. It's designed to display important messages or notifications to users. Alerts come in different contextual styles (such as success, info, warning, and danger) and can contain text, icons, and optional close buttons.

How do you create a basic Bootstrap Alert?

To create a basic Bootstrap Alert, you can use the following HTML structure:

<div class="alert alert-primary" role="alert">
  This is a primary alert—check it out!
</div>

In this example, the alert class is used along with the contextual class alert-primary to define the styling of the alert. The role="alert" attribute helps screen readers to identify the element as an alert for accessibility purposes.

What are the contextual classes in Bootstrap Alerts?

Bootstrap Alerts use contextual classes to provide different visual styles based on the type of message. The available contextual classes are:

  • alert-success: Indicates a successful operation.
  • alert-info: Provides informational messages.
  • alert-warning: Indicates a warning or caution.
  • alert-danger: Indicates an error or critical message.

You can apply these classes to the alert element to change the appearance of the alert accordingly.

How can you add a close button to a Bootstrap Alert?

To add a close button to a Bootstrap Alert, you can include a button element with the close class within the alert div. Here's an example:

<div class="alert alert-warning alert-dismissible fade show" role="alert">
  This is a warning alert with a close button.
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

In this example, the alert-dismissible class and a button with the btn-close class are added. The data-bs-dismiss="alert" attribute on the button allows it to close the alert when clicked.

Can you use icons within Bootstrap Alerts?

Yes, you can include icons within Bootstrap Alerts. You can use icon fonts like Font Awesome or Bootstrap Icons. To add an icon, insert the icon's HTML code or class inside the alert's content. For example:

<div class="alert alert-info" role="alert">
  <i class="fas fa-info-circle"></i> This is an informational alert.
</div>

In this example, the Font Awesome icon for an information circle is added before the alert's content.

How can you stack multiple Bootstrap Alerts?

To stack multiple Bootstrap Alerts, you can simply place them one after another within a container, such as a div element. Each alert will automatically stack vertically. Here's an example:

<div class="container">
  <div class="alert alert-success" role="alert">
    Success message.
  </div>
  <div class="alert alert-info" role="alert">
    Informational message.
  </div>
  <div class="alert alert-warning" role="alert">
    Warning message.
  </div>
</div>

Can you customize the duration of Bootstrap Alert auto-closing?

By default, Bootstrap Alerts with the alert-dismissible class and a close button will remain open until the user manually closes them. If you want to automatically close the alerts after a certain duration, you'll need to use JavaScript. Here's a simple example using jQuery:

<div class="alert alert-warning alert-dismissible fade show" role="alert" id="autoCloseAlert">
  This alert will close automatically after 5 seconds.
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

<script>
    $(document).ready(function () {
        setTimeout(function () {
            $("#autoCloseAlert").alert("close");
        }, 5000);
    });
</script>

In this example, the setTimeout function is used to close the alert after 5 seconds.

How can you make Bootstrap Alerts full-width?

By default, Bootstrap Alerts are responsive and inherit their width from their container. If you want to make them full-width, you'll need to override the default container width. You can place your alerts within a container with custom CSS that stretches it to full-width, like this:

<style>
  .full-width-container {
    width: 100%;
    padding-right: 0;
    padding-left: 0;
    margin-right: auto;
    margin-left: auto;
  }
</style>

<div class="container full-width-container">
  <div class="alert alert-info" role="alert">
    This is a full-width alert.
  </div>
</div>

Remember that changing the width of components can affect the overall layout, so ensure that it aligns with your design intentions.

How can you make Bootstrap Alerts slide in from the top or bottom of the page?

By default, Bootstrap Alerts appear using a fade animation. If you want to make them slide in from the top or bottom, you'll need to apply custom CSS animations. Here's an example of creating a slide-in effect from the top:

<style>
  .slide-in-top {
    opacity: 0;
    transform: translateY(-100%);
    transition: opacity 0.3s, transform 0.3s;
  }

  .slide-in-top.show {
    opacity: 1;
    transform: translateY(0);
  }
</style>

<div class="alert alert-info slide-in-top" role="alert">
  This alert slides in from the top.
</div>

In this example, the .slide-in-top class defines the initial position and opacity, and the .show class adjusts these properties to reveal the alert with a slide-in animation. Similar CSS can be applied for a slide-in effect from the bottom.

How can you create a Bootstrap alert with a link?

To create a Bootstrap alert message with a link, you can simply wrap the alert content or parts of it in an anchor (<a>) tag:

<div class="alert alert-info" role="alert">
  Click <a href="#" class="alert-link">here</a> for more information.
</div>

The alert-link class provides styling to make the link within the alert stand out.

How can you create a multi-line alert message?

By default, alert messages in Bootstrap are inline elements. To create a multi-line alert message, you can use line breaks (<br>) or wrap each line in separate elements like <p>:

<div class="alert alert-warning" role="alert">
  <p>This is the first line.</p>
  <p>This is the second line.</p>
</div>

Alternatively, you can apply custom CSS to make the alert block-level and control its dimensions.

How can you create a Bootstrap alert with a custom title?

Bootstrap doesn't have a built-in feature for adding a separate title to alert messages. However, you can simulate a title by adding a heading element (<h4>, for instance) within the alert:

<div class="alert alert-danger" role="alert">
  <h4 class="alert-heading">Attention!</h4>
  This is an important alert message.
</div>

In this example, the <h4> element is styled to resemble a title.

How can you create a fade-in animation for alert messages?

By default, Bootstrap alert messages already include a fade-in animation. If you'd like to add a fade-in effect when an alert is displayed dynamically, you can use the fade and show classes:

<div class="alert alert-success fade show" role="alert">
  This alert will fade in.
</div>

The show class triggers the fade-in animation when combined with the fade class.

How can you change the appearance of the alert's border?

You can change the appearance of the alert's border using custom CSS. Here's an example of how to change the border color and width:

<style>
  .custom-border {
    border: 2px solid #ffc107; /* Change the color as needed */
  }
</style>

<div class="alert alert-warning custom-border" role="alert">
  This alert has a custom border.
</div>

By adding the custom-border class and defining your desired border properties in the associated CSS, you can achieve the desired look.

How can you create a Bootstrap alert that is centered on the page?

To center a Bootstrap alert vertically and horizontally on the page, you can use flexbox or CSS Grid. Here's an example using flexbox:

<style>
  .center-alert {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
  }
</style>

<div class="center-alert">
  <div class="alert alert-warning" role="alert">
    This alert is centered on the page.
  </div>
</div>

flex and using justify-content and align-items properties, you can center the alert both vertically and horizontally.

How can you adjust the padding of a Bootstrap alert?

You can adjust the padding of a Bootstrap alert using custom CSS to control its spacing. Here's an example:

<style>
  .custom-padding {
    padding: 20px; /* Adjust the value as needed */
  }
</style>

<div class="alert alert-success custom-padding" role="alert">
  This alert has custom padding.
</div>

By applying the custom-padding class and defining your desired padding value in the associated CSS, you can change the spacing around the alert's content.

How can you create a Bootstrap alert that is only shown on larger screens?

You can use Bootstrap's responsive classes to show or hide alerts based on screen sizes. Here's an example of an alert that's shown only on screens larger than lg (large):

<div class="alert alert-primary d-none d-lg-block" role="alert">
  This alert is shown on larger screens.
</div>

By using the d-none class to hide the alert by default and the d-lg-block class to show it on large screens and above, you can control the alert's visibility based on screen size.

How can you add a custom background color to a Bootstrap alert?

To add a custom background color to a Bootstrap alert, you can use custom CSS to override the default styling. Here's an example:

<style>
  .custom-background {
    background-color: #ffcc00; /* Set your desired background color */
  }
</style>

<div class="alert alert-warning custom-background" role="alert">
  This alert has a custom background color.
</div>

By applying the custom-background class and defining your desired background color in the associated CSS, you can change the alert's background color.

How can you align the text content of a Bootstrap alert?

You can align the text content of a Bootstrap alert using Bootstrap's text alignment classes. Here's an example:

<div class="alert alert-info text-center" role="alert">
  This alert has centered text.
</div>

By applying the text-center class, you can align the alert's text content to the center. Similarly, you can use text-left, text-right, or text-justify classes for other alignments.

What if I want to use Bootstrap Icons instead of Font Awesome?

If you're using Bootstrap Icons, you can use the icon's classes directly within the alert content. Here's an example:

<div class="alert alert-info" role="alert">
  <span class="bi bi-info-circle"></span>
  This is an informational alert with a Bootstrap icon.
</div>

In this case, the bi bi-info-circle class is used to display a Bootstrap icon before the alert message.

Can I add icons to dismiss buttons in Bootstrap alerts?

Yes, you can add icons to dismiss buttons in Bootstrap alerts by placing the icon within the button element. Here's an example using Font Awesome:

<div class="alert alert-primary alert-dismissible fade show" role="alert">
  This is a primary alert with a close button.
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close">
    <i class="fas fa-times"></i>
  </button>
</div>

In this example, the Font Awesome class fas fa-times is used to add an "x" icon to the close button.

How can I make the icon and text in an alert appear on the same line?

By default, the icon and text in an alert may appear on separate lines. You can use CSS to adjust their display properties. Here's an example using Font Awesome:

<style>
  .icon-and-text {
    display: flex;
    align-items: center;
  }
</style>

<div class="alert alert-info" role="alert">
  <div class="icon-and-text">
    <i class="fas fa-info-circle"></i>
    <span>This is an alert with an icon and text on the same line.</span>
  </div>
</div>

flex property is used to align the icon and text on the same line.

How can I vertically align an icon within the alert?

To vertically align an icon within the alert, you can use CSS to control the alignment of the icon. Here's an example using Font Awesome:

<style>
  .icon-vertical-align {
    display: flex;
    align-items: center;
  }
</style>

<div class="alert alert-success" role="alert">
  <div class="icon-vertical-align">
    <i class="fas fa-check-circle"></i>
    <span>This is a success alert with a vertically aligned icon.</span>
  </div>
</div>

flex and align-items: center properties are used to vertically align the icon and text.

How can I make the icon and alert content responsive on smaller screens?

To make the icon and alert content responsive on smaller screens, you can use Bootstrap's responsive classes along with your custom CSS. For example:

<div class="alert alert-danger" role="alert">
  <div class="d-flex justify-content-center align-items-center">
    <i class="fas fa-exclamation-circle"></i>
    <span class="ms-2">This is a responsive alert.</span>
  </div>
</div>

In this example, the d-flex, justify-content-center, and align-items-center classes are used to center the icon and content horizontally and vertically on smaller screens.

How can I animate icons within Bootstrap alerts?

You can animate icons within Bootstrap alerts using CSS animations or transitions. For example, you can add a hover effect to the icon:

<style>
  .icon-hover:hover {
    transform: rotate(45deg);
    transition: transform 0.3s;
  }
</style>

<div class="alert alert-primary" role="alert">
  <i class="fas fa-star icon-hover"></i>
  Hover over the icon to see an animation.
</div>

In this example, the icon will rotate by 45 degrees when hovered over, creating a simple animation effect.

Can I include additional content such as headings, paragraphs, or buttons within a Bootstrap alert?

Yes, you can include various types of additional content within a Bootstrap alert to provide more context or actions. This can include headings, paragraphs, buttons, links, or any other HTML elements.

How do I structure an alert to include additional content?

You can structure an alert to include additional content by placing the content within the alert's HTML structure. Here's an example:

<div class="alert alert-info" role="alert">
  <h4 class="alert-heading">Additional Content</h4>
  <p>This alert includes a heading and a paragraph of additional content.</p>
  <a href="#" class="btn btn-primary">Learn More</a>
</div>

In this example, a heading, paragraph, and a button are added within the alert.

Can I use multiple data-bs-dismiss attributes within the same alert?

Yes, you can use multiple data-bs-dismiss attributes within the same alert to enable closing from multiple dismissible elements. For example, you can have a button and a link both set to close the alert:

<div class="alert alert-warning alert-dismissible fade show" role="alert">
  This is a warning alert.
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
  <a href="#" class="alert-link" data-bs-dismiss="alert">Dismiss using link</a>
</div>

Both the button and the link will close the alert when clicked.

What are the different methods available for closing Bootstrap alerts programmatically?

Bootstrap provides two main methods for closing alerts programmatically:

  • alert("close"): This method closes the alert by triggering the fade-out animation. It works by adding the d-none class to hide the alert and adding the fade class to trigger the fade-out animation.
  • alert("dispose"): This method completely removes the alert from the DOM. It's useful when you want to remove the alert and its associated JavaScript data entirely.

How can I use the alert("close") method in JavaScript?

To use the alert("close") method in JavaScript, you need to select the alert element and call the method on it. Here's an example:

<div class="alert alert-warning alert-dismissible fade show" role="alert" id="myAlert">
  This is a warning alert.
  <button type="button" class="btn-close" aria-label="Close"></button>
</div>

<script>
  const myAlert = document.getElementById("myAlert");
  const closeButton = myAlert.querySelector(".btn-close");

  closeButton.addEventListener("click", () => {
    myAlert.alert("close"); // Close the alert using the method
  });
</script>

In this example, clicking the close button will close the alert using the alert("close") method.


Conclusion

Bootstrap Alert serves as a robust and versatile component for delivering dynamic and responsive notifications within web applications. With features like Notification Boxes, Dynamic Alert Messages, and Responsive Alert Components, Bootstrap Alert ensures a seamless and user-friendly interaction with crucial information.

The provision of Dismissible Pop-ups and Alert Notifications offers an effective way to convey messages to users, fostering a more engaging and interactive user experience. User-Friendly Notification Boxes and Interactive Alert Bars contribute to a design that prioritizes ease of use.

The flexibility of Dynamic Alert Display and Popup Message Notifications accommodates varying content needs, ensuring that information is presented in an informative and visually appealing manner. Whether it's Informative Notification Boxes or Attention-Grabbing Alerts, Bootstrap Alert provides customizable design options to match specific communication requirements.

Additionally, the component is tailored for adaptability, offering Customizable Alert Design and Mobile-Friendly Notification Boxes that seamlessly adjust to diverse screen sizes and devices. Moreover, Bootstrap Alert ensures consistency in design with Consistent Link Styling in Alerts and Coordinated Link Colors in Alerts, contributing to a visually harmonious user interface.

The integration of Iconic Alerts and Enhanced Alert Messages introduces visual elements, enhancing the overall communicative impact. Features like Matching Links in Alert Boxes, Alert Icons Integration, and Embedding Extra Content in Alerts provide additional layers of information and interaction.