Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to Use CSS Alerts and Provide Good Feedback for Users

Would you like to learn how to create alert messages and style them using CSS? Alerts are an important design element in web development, providing visual feedback to users.

For example, you can use them to notify users that an order is successful, or an error occurred while performing certain actions on your site.

In this tutorial, we’ll explain how CSS alerts work and the different available alert types. Then we’ll show you how to style alert messages using CSS. Let’s begin.

Understanding How CSS Alert Works

CSS alerts serve as essential components in web design, offering a visually impactful way to communicate messages, feedback, or warnings to users. To fully understand how they work under the hood, you’ll need to know the components of a standard alert message. Below, we’ll explain each of the components.

Breakdown of Alert Components

Container

The container is the outer box that encapsulates the entire alert. It provides structure and serves as the primary visual element. Typically, it encloses the text and any additional components like icons or illustrations.

Text

The text component is where the actual message or information is displayed. This is the core content of the alert, conveying the intended communication to the user. The styling of this text is crucial for readability and visual appeal.

Close Button

The close button is an optional element within an alert, allowing users to dismiss or close the alert. It provides interactivity and convenience for users who may want to remove the alert from their view. The close button can be styled to match the overall design of the alert.

Now you know the components of alert messages, let’s discuss some of the most commonly used alert types in modern web development.

Different Types of Alerts

CSS alerts come in various types, each serving a specific purpose. Below are the most popular alert types:

Success Alerts

Success alerts communicate the successful completion of an operation or task. They often use positive colors like green to stimulate a sense of accomplishment.

Success alert component

Error Alerts

Error alerts indicate that something has gone wrong or an error has occurred. These alerts are also known as danger alerts and typically use red tones to alert users to issues that require attention.

error messages alert

Warning Alerts

Warning messages alert users to potential problems or issues that may arise. They use colors like yellow or orange to convey a sense of caution.

Warning message alert example

Info Alerts

Info alerts provide general information to users. They are often used for non-critical messages or announcements and use neutral colors.

Info alert display example

Basic CSS Alert Styling

To create a basic CSS alert, we’ll start with a simple structure and gradually enhance it. This step-by-step guide will cover styling a basic alert, customization options for colors and typography, and how to add icons for a more engaging visual experience.

Prerequisites

To follow along with this tutorial, you’ll need to have a basic understanding of HTML and CSS. Check out the video below if you need a refresher on both concepts.

If you’d like to speed up your development time, we suggest using tools like PureCode to automatically generate components for your web project. PureCode provides over 1000 AI-generated templates that can be integrated into web apps built using CSS3, Tailwind CSS, and Material UI.

Explore PureCode Templates

Creating an Alert Message

Let’s begin by setting up the basic HTML structure for an alert. We’ll create a container with a message and an optional close button.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>CSS Alert Demo</title>
</head>
<body>

<div class="alert">
  <p>This is a basic alert message.</p>
  <span class="close-btn">&times;</span>
</div>

</body>
</html>

Now, let’s add some basic styles to our alert. We’ll give it a background color, padding, border, and position the close button.

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 20px;
}

.alert {
  padding: 15px;
  border: 1px solid #ddd;
  background-color: #f9f9f9;
  color: #333;
  position: relative;
  margin-bottom: 20px;
  border-radius: 5px;
}

.close-btn {
  position: absolute;
  top: 24px;
  right: 16px;
  font-size: 20px;
  cursor: pointer;
}

This creates a simple info alert with a light gray background color, a border, and a close button positioned on the right side of the container.

Default info alert

Customizing Colors and Typography

Let’s explore customization options by creating alerts with different colors and typography. In this section, we’ll demonstrate success, error, warning, and info alerts.

Here are the CSS styles we’ll use for each alert type.

.success {
  background-color: #d4edda;
  border-color: #c3e6cb;
  color: #155724;
}

.error {
  background-color: #f8d7da;
  border-color: #f5c6cb;
  color: #721c24;
}

.warning {
  background-color: #fff3cd;
  border-color: #ffeeba;
  color: #856404;
}

.info {
  background-color: #d1ecf1;
  border-color: #bee5eb;
  color: #0c5460;
}

Now, you can apply these classes to your alerts to signify different types in your HTML markup.

<div class="alert success">
  <p>Success alert: Your action was successful!</p>
  <span class="close-btn">&times;</span>
</div>

<div class="alert error">
  <p>Error alert: Something went wrong.</p>
  <span class="close-btn">&times;</span>
</div>

<div class="alert warning">
  <p>Warning alert: Proceed with caution.</p>
  <span class="close-btn">&times;</span>
</div>

<div class="alert info">
  <p>Info alert: Just an informational message.</p>
  <span class="close-btn">&times;</span>
</div>

When you preview your page, you’ll see alert messages of different types.

Alert box examples

Adding Icons to Alert Boxes

You can include icons in your alert messages to make them visually appealing to users. To do so, you’ll first need to add the icon library you intend to use to your HTML markup.

For this example, we’ll use the Font Awesome library. Go ahead and add the code below to your HTML head tag to import the library.

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.1.0/css/all.css" integrity="sha512-ajhUYg8JAATDFejqbeN7KbF2zyPbbqz04dgOLyGcYEk/MJD3V+HJhJLKvJ2VVlqrr4PwHeGTTWxbI+8teA7snw==" crossorigin="anonymous" referrerpolicy="no-referrer" />

Next, we’ll create a success alert that includes the checkbox icon. Here is the code snippet for it.

<div class="alert success">
<i class="fas fa-check-circle"></i>
  <p>Success alert: Your action was successful!</p>
  <span class="close-btn">&times;</span>
</div>

In the CSS, we’ll style both the alert box and the icon to match the styles for a success alert.

.alert {
  padding: 15px;
  border: 1px solid #ddd;
  background-color: #f9f9f9;
  color: #333;
  position: relative;
  margin-bottom: 20px;
  border-radius: 5px;
}

.success {
  display: flex;
  align-items: center;
  background-color: #d4edda;
  border-color: #c3e6cb;
  color: #155724;
}

/* Icon styling */
.alert i {
  margin-right: 10px;
  font-size: 20px;
}

Here is how it looks when you preview your code.

Alert message with icon example

You can use any supported icon for your alert messages and customize the text and background color to suit your specifications.

Dismissing Alert Boxes on Click Event

If you’d like, you can use JavaScript to improve the alert message to dismiss once the user clicks on the close button. Here is an example implementation.

HTML:


  <!-- Closeable Success Alert with Checkmark Icon -->
  <div class="alert alert-success">
    <span>Your operation was successful!</span>
    <!-- Close icon -->
    <span class="close-icon" onclick="this.parentElement.style.display='none';">&times;</span>
  </div>

CSS:

    /* Basic styling for the alert */
    .alert {
      position: relative;
      padding: 15px;
      border: 1px solid #ddd;
      border-radius: 4px;
      margin: 15px 0;
      display: flex;
      align-items: center;
    }

    /* Close icon styling */
    .close-icon {
      position: absolute;
      top: 5px;
      right: 5px;
      cursor: pointer;
    }

    /* Success alert style */
    .alert-success {
      background-color: #dff0d8;
      border-color: #d6e9c6;
      color: #3c763d;
    }

In this example, the close icon (&times;) is positioned at the top-right corner of the alert. The onclick attribute on the close icon triggers a JavaScript function to set the display property of the alert’s parent element to ‘none‘. This essentially hides the alert when the close icon is clicked.

Advanced CSS Alert Styling

Enhancing CSS alerts goes beyond the basics. In this section, we’ll explore advanced styling options to create eye-catching and dynamic alerts.

We’ll cover using CSS animations for entrance and exit effects, employing transitions for interactive alerts, and ensuring responsiveness across various screen sizes.

Using CSS Animations for Alert Entrance and Exit Effects

CSS animations add a touch of refinement to alert messages. Let’s implement a simple sliding animation for alert entrance and exit.

@keyframes slideIn {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0);
  }
}

@keyframes slideOut {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(-100%);
  }
}

.alert {
  padding: 15px;
  border: 1px solid #ddd;
  background-color: #f9f9f9;
  color: #333;
  position: relative;
  margin-bottom: 20px;
  border-radius: 5px;
  animation: slideIn 0.5s ease-out; /* Animation property */
}

.alert.hide {
  animation: slideOut 0.5s ease-in forwards;
}

We’ll use JavaScript to hide the alert message once the user clicks the hide button. Here is the code we’ll use to implement this logic.

const alert = document.querySelector('.alert');

// Adding an event listener to hide the alert
alert.addEventListener('click', () => {
  alert.classList.add('hide');
});

In this example, the alert slides in when displayed and slides out when clicked, demonstrating how CSS animations can add flair to alert interactions.

Slide-in and slide-out effects

Creating Dynamic or Interactive Alerts with CSS Transitions

CSS transitions enable smooth state changes within alerts. Let’s use transitions for a subtle color change when hovering over an alert.

.alert {
  transition: background-color 0.3s ease-in-out;
}

.alert:hover {
  background-color: #e74c3c;
  color: #fff;
}

In this snippet, the alert smoothly transitions its background color when hovered, providing a responsive and interactive feel to the alert.

Styling Alerts for Responsiveness Across Different Screen Sizes

Ensuring that alerts look good on various devices is essential. Let’s use media queries to adjust alert styles based on screen width.

@media (max-width: 768px) {
  .alert {
    font-size: 14px;
  }
}

This media query adjusts the font size of alerts for screens with a maximum width of 768 pixels, ensuring readability and a pleasing appearance on smaller devices.

CSS Frameworks for Alerts

CSS frameworks simplify the process of styling and designing alerts. They offer pre-built alert components that you can easily integrate into your projects. In this section, we’ll cover three popular CSS frameworks—Bootstrap, Tailwind CSS, and Semantic UI.

Bootstrap

Bootstrap is a widely used front-end framework known for its extensive set of pre-styled components, including alerts. To use Bootstrap alerts, you’ll need to include the Bootstrap CSS and JS files in your HTML. Then you can use the alert class to quickly create an alert on your project:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <title>Bootstrap Alerts</title>
</head>
<body>

<div class="alert alert-success" role="alert">
  This is a success alert!
</div>

<div class="alert alert-danger" role="alert">
  This is an error alert!
</div>

</body>
</html>
BootStrap alert example

Overview

  • Ease of Use: Bootstrap provides ready-to-use alert classes, making it straightforward to implement various alert types.

  • Customization: While Bootstrap alerts offer some customization options, they might not be as flexible as other frameworks like Tailwind.

  • Community Support: Bootstrap has a large and active community, ensuring continuous support and updates.

Tailwind CSS

Tailwind is a utility-first CSS framework that provides low-level utility classes for building designs directly in your markup. To use alerts in a Tailwind project, you’ll need to include the Tailwind CSS import in your HTML and utilize the utility classes:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css">
  <title>Tailwind CSS Alerts</title>
</head>
<body>

<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative" role="alert">
  This is a success alert!
</div>

<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
  This is an error alert!
</div>

</body>
</html>
Tailwind CSS alert example

Overview

  • Flexibility: Tailwind provides a more flexible and customizable approach with utility classes. This allows you to tailor alerts to specific design requirements.

  • Learning Curve: Tailwind has a steeper learning curve compared to Bootstrap, especially if you’re not familiar with utility-first frameworks.

  • File Size: Tailwind allows you to generate a smaller CSS file by only including the utility classes you need.

Semantic UI

Semantic UI is a modern front-end development framework that emphasizes human-friendly HTML. To use Semantic UI alerts, include the Semantic UI CSS and JS import in your HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
  <title>Semantic UI Alerts</title>
</head>
<body>

<div class="ui success message">
  <i class="close icon"></i>
  <div class="header">
    This is a success alert!
  </div>
</div>

<div class="ui error message">
  <i class="close icon"></i>
  <div class="header">
    This is an error alert!
  </div>
</div>

</body>
</html>
Example of Semantic UI alert message

Overview

  • Human-Friendly HTML: Semantic UI promotes clean and human-readable HTML, making it intuitive to use and understand.

  • Styling Components: Alerts in Semantic UI come with predefined styles, offering a polished appearance out of the box.

  • Component Variety: Semantic UI provides a wide range of components for various purposes, ensuring consistency in design.

CSS Alerts Frameworks Comparison Table

BootstrapTailwind CSSSemantic UI
ProsReady-made components and responsive designUtility-first approach with low file sizeHuman-readable classes and support component theming
ConsLarge file sizePotential for bloated HTMLLimited customization options
FlexibilityNot very flexible Very customizableModerately flexible
Ease of UseEasy to use with predefined classesRequires more manual configuration but provides flexibilityUses semantic and human-friendly class names
Learning CurveModerateHighModerate to High
When to use?If you require a quick and standard solutionIf you want full control over styling your componentsIf you prefer a human-readable code base.

Accessibility Considerations

Styling CSS alerts can enhance the visual appeal of your web application. However, it’s crucial to prioritize accessibility to ensure all users, including those with disabilities, have a seamless experience.

Here are essential accessibility considerations to keep in mind when styling alerts in CSS:

1. Semantically Meaningful Structure

Ensure that the HTML structure of your styled alerts is semantically meaningful. Use appropriate HTML elements and attributes to convey the purpose and content of the alerts.

<div role="alert" class="custom-alert"> 
   <p>This is an important alert message.</p> 
</div>

2. High Contrast and Readability

Choose color combinations that provide sufficient contrast for users with visual impairments. Ensure text is easily readable against the background color to accommodate individuals with low vision.

3. Responsive Design for Different Viewports

Make sure your alert styles adapt well to different screen sizes. Responsive design ensures that users on various devices can access and interact with alerts comfortably.

4. Provide Clear Instructions

Include clear and concise instructions within your alerts, especially if user interaction is required. This helps the user to understand the context and purpose of the alert.

Frequently Asked Questions

These are answers to some of the top questions about styling alert messages with CSS.

What are CSS alerts?

CSS alerts, or alert boxes, are user interface components used to convey important information or messages to users on a webpage. They are often used to provide feedback, warnings, or notifications. CSS is used to style and position these alerts on the page.

What are the CSS notification colors?

CSS notification colors can vary based on the design, but common colors include:

  • Success: #4CAF50 (Green)

  • Error: #f44336 (Red)

  • Warning: #ff9800 (Orange)

  • Info: #2196F3 (Blue)

What’s the best way to make responsive alerts for mobile devices?

To make alerts responsive for mobile devices, use relative units like percentages for widths. In addition, we suggest using media queries in your CSS to adjust styles based on the screen size. Ensure that the alert content and button sizes adapt well to smaller screens.

Which CSS framework is recommended for quickly implementing alerts?

Bootstrap is a popular CSS framework that provides a variety of pre-designed components, including alerts. It offers a simple way to implement and customize alerts without having to write extensive CSS code. Other frameworks like Bulma and Foundation also provide similar components for easy implementation.

Final Thoughts on Creating Alert Messages

Alert messages provide information to your website viewers on specific actions like successful registration.

In this tutorial, we explained how CSS alerts work and showed you how to create and style alert messages with CSS. We also covered some advanced concepts like adding animations to alert boxes.

If you’re using CSS for your project, check out some of PureCode’s components. Purecode provides many AI-generated custom components including alert components that you can easily integrate into your project.

Further Reading

If this guide was helpful to you, consider checking out other tutorials to help you become a better developer.

Also check out the video below to learn more about creating alerts in CSS.

David Ozokoye

David Ozokoye

Software Engineer and Technical Writer