How to create: warning messages

Learn how to use CSS to create warning messages.

Warning

Warning messages can be used to notify users of some special matters: danger, success, information, or warning.

× Danger!indicating dangerous or potentially negative operations.
× Success!indicating successful or positive operations.
× Information!indicating neutral information changes or operations.
× Warning!indicating a warning that may need attention.

Probeer het zelf

Create a warning message

Step 1 - Add HTML:

<div class="alert">
  <span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
  This is an alert box.
</div>

If you want to be able to close the warning message, add a onclick attribute <span> element, the attribute indicates "When you click me, hide my parent element" - that is, the container <div class="alert">.

Tip:Use the HTML entity "×" to create the letter "x".

Step 2 - Add CSS:

Set the style of the warning box and close button:

/* Warning message box */
.alert {
  padding: 20px;
  background-color: #f44336; /* Red */
  color: white;
  margin-bottom: 15px;
}
/* Close button */
.closebtn {
  margin-left: 15px;
  color: white;
  font-weight: bold;
  float: right;
  font-size: 22px;
  line-height: 20px;
  cursor: pointer;
  transition: 0.3s;
}
/* When the mouse moves over the close button */
.closebtn:hover {
  color: black;
}

Probeer het zelf

multiple warnings

If there are multiple warning messages on the page, you can add the following script to <span> of the onclick properties to close different warnings.

And if you want the warnings to fade out slowly when clicked, add opacity and transition to alert In class:

Example

<style>
.alert {
  opacity: 1;
  transition: opacity 0.6s; /* 600 milliseconds fade out */
}
</style>
<script>
// Get all elements with class="closebtn"
var close = document.getElementsByClassName("closebtn");
var i;
// Loop through all close buttons
for (i = 0; i < close.length; i++) {
  // Traverse all close buttons
  close[i].onclick = function(){
    // Get the parent element of <span class="closebtn"> (<div class="alert">)
    var div = this.parentElement;
    // Set the opacity of div to 0 (transparent)
    div.style.opacity = "0";
    // 600 milliseconds later hide div (same as fade out time)
    setTimeout(function(){ div.style.display = "none"; }, 600);
  }
}
</script>

Probeer het zelf

Gerelateerde pagina's

Tutorial:Hoe notities te maken