How to create alert messages with CSS?


The alert message can be seen on web pages. As an example, we can consider a message while deleted an account on a social media website. Even coupons are provided in the form of alert message on some websites. Other examples can be “Your order is confirmed” or even ““Your password is about to expire. Please update it now.” Let us see how to create alert messages with HTML and CSS.

Create a container for the alerts

A div is set for the alter message. Within that the alert message is set with the close button symbol −

<div class="alertMessage">
   <span class="close" onclick="this.parentElement.style.display='none';">×</span>
   <strong>This cannot be revered!</strong> Your account will be deleted.
</div>

Style the alert

We have set the background color for the alert message using the background-color property −

.alertMessage {
   padding: 20px;
   background-color: #f44336;
   color: white;
   font-size: 20px;
}

Close button on an alert

A close button is visible on an alert message so the user can remove the close button after reading. The symbol for the close is x −

<span class="close" onclick="this.parentElement.style.display='none';">×</span>

Position the close button

The x that appears like a close button is styled like this. The close button is positioned using the float property with the value right. The transition is set using the transition property −

.close{
   margin-left: 15px;
   color: white;
   font-weight: bold;
   float: right;
   font-size: 22px;
   line-height: 20px;
   cursor: pointer;
   transition: 0.3s;
}

Example

To create alert messages with CSS, the code is as follows −

<!DOCTYPE html>
<html>
<head>
   <style>
      body{
         font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      }
      .alertMessage {
         padding: 20px;
         background-color: #f44336;
         color: white;
         font-size: 20px;
      }
      .close{
         margin-left: 15px;
         color: white;
         font-weight: bold;
         float: right;
         font-size: 22px;
         line-height: 20px;
         cursor: pointer;
         transition: 0.3s;
      }
      .close:hover {
         color: black;
      }
   </style>
</head>
<body>
   <h1>Alert Message Example</h1>
   <div class="alertMessage">
      <span class="close" onclick="this.parentElement.style.display='none';">×</span>
      <strong>This cannot be revered!</strong> Your account will be deleted.
   </div>
</body>
</html>

Updated on: 14-Dec-2023

640 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements