How to Create: Warning Messages
- Previous Page Product Card
- Next Page Prompt Box
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.
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, please add a onclick
attribute <span>
element, the attribute indicates "hide my parent element when I am clicked" - that is, the container <div class="alert">
.
Tip:Use the HTML entity "×" to create the letter "x".
Step 2 - Add CSS:
Set the styles for the alert box and close button:
/* Alert 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; }
multiple alerts
If there are multiple alert messages on the page, you can add the following script to <span>
of the element onclick
properties to close different alerts.
And if you want the alerts to fade out slowly when clicked, add opacity and transition to alert
In class:
Example
<style> .alert { opacity: 1; transition: opacity 0.6s; /* Fade out over 600 milliseconds */ } </style> <script> // Get all elements with class="closebtn" var close = document.getElementsByClassName("closebtn"); var i; // Loop through all close buttons Loop through all close buttons for (i = 0; i < close.length; i++) { // Loop through 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"; // Hide div after 600 milliseconds (same as fade-out time) setTimeout(function(){ div.style.display = "none"; }, 600); } } </script>
Related Pages
Tutorial:How to Create a Sticky Note
- Previous Page Product Card
- Next Page Prompt Box