Bootstrap Alerts

Alert messages are useful for the websites every now and then. They might indicate some failed validation or notify a successful registration for the user.

Either way, their appearance is an important aspect to work on. Bootstrap 4 has many features for Alert Messages as well.

It provides the developers some easy ways in which they can create and style predefined alert messages.

The class, generally, used for the Alerts is the .alert class. There are 4 contextual classes that can be used for different types of alerts:

  • .alert-success: Background color – Green. Any positive ‘successful’ action can be notified using this alert.
  • .alert-info: Background color – Light-blue. This is just an information that the user needs to be notified about. Generally any informative action is indicated using this alert.
  • .alert-warning: Background color – Yellow. This is different from alert-danger as this can be used to suggest some caution to avoid any potentially negative action rather than notifying it.
  • .alert-danger: Background color – Red. This indicates any dangerous i.e. potentially negative action.

Here’s the sample code for using these classes:

Apart from these 4, there are some other classes that can be used for different purposes with alerts. Let’s have a look

Alert Links

You can add some matching links with matching foreground and background colors using the .alert-link class. This links can be used to redirect the user to some detailed information about the alert.

Closing Alerts

In some cases, the user may want to remove the alert ones they have addressed it.

This can be done by using dismissible or closable alerts. In order to do this you can use the .alert-dismissible class to the alert container.

You also need to add class=”close” and data-dismiss=“alert” to some link or a button element. Therefore, when you click on this element the alert box will disappear.

Here’s the code to understand this better:

Observe the ‘aria-label’ and ‘&times’ in the above code. 

These two have an important role in this code. The aria-label= “close” attribute is there to have a better accessibility for the close button.

The ‘&times’ or the (×) is actually a better and more preferable way of indicating the close button instead of using the ‘x’ symbol.

Animated Alerts

The two classes used to add an animated fade effect for when closing the alert messages are .fade and .in.

Close Alerts via data-* Attributes

Another way of creating a dismissible alert is by using the data-dismiss=“alert” attribute to any link/button element.

Just like the .alert-dismissible class, this too shall close the alert message using the link/button element.

Sample code: