¿Cómo crear: mensaje de alerta

Aprende a crear mensajes de alerta usando CSS.

¡Advertencia!

Los mensajes de alerta se pueden usar para notificar al usuario sobre asuntos especiales: peligro, éxito, información o advertencia.

× ¡Peligro!representa una operación peligrosa o que puede tener efectos negativos.
× ¡Éxito!representa una operación exitosa o positiva.
× ¡Información!representa un cambio de información neutral o una operación.
× ¡Advertencia!representa una advertencia posible que debe tenerse en cuenta.

Prueba por tu cuenta

Crear un mensaje de alerta

Paso 1 - Añadir HTML:

<div class="alert">
  <span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
  Este es un cuadro de alerta.
</div>

Si desea poder cerrar el mensaje de alerta, agregue una onclick propiedad <span> elemento, esta propiedad indica "ocultar mi elemento padre al hacer clic en mí" - es decir, el contenedor <div class="alert">.

Consejo:Utilice el carácter especial HTML "×" para crear la letra "x".

Segundo paso - Añadir 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;
}

Prueba por tu cuenta

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 alerts.

And if you want them 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++) {
  // 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 div's opacity 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>

Prueba por tu cuenta

Páginas relacionadas

Tutoriales:¿Cómo se crea una nota?