How to Create: Snackbar / Toast

Learn how to create Snackbar/Toast using CSS and JavaScript.

Snackbar / Toast

Snackbar is usually used as a tooltip/popup window to display messages at the bottom of the screen.

Click the button to show Snackbar. It will disappear after 3 seconds.

Some text some message..

Create Snackbar

Step 1 - Add HTML:

<!-- Use button to open snackbar -->
<button onclick="myFunction()">Show Snackbar</button>
<!-- Actual snackbar -->
<div id="snackbar">Some text some message..</div>

Step 2 - Add CSS:

Set the style of snackbar and add animation:

/* snackbar - Position it at the bottom and center of the screen */
#snackbar {
  visibility: hidden; /* Hidden by default, visible on click */
  min-width: 250px; /* Set default minimum width */
  margin-left: -125px; /* Divide the min-width value by 2 */
  background-color: #333; /* Black background color */
  color: #fff; /* White text color */
  text-align: center; /* Centered text */
  border-radius: 2px; /* Rounded border */
  padding: 16px; /* Padding */
  position: fixed; /* Fixed at the top of the screen */
  z-index: 1; /* Add z-index if needed */
  left: 50%; /* Center the snackbar */
  bottom: 30px; /* Distance from the bottom 30px */
}
/* Show the snackbar when the button is clicked (class added by JavaScript) */
#snackbar.show {
  visibility: visible; /* Show the snackbar */
  /* Add animation: fade in and out the snackbar over 0.5 seconds. However, delay the fade-out process by 2.5 seconds. */
  -webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
  animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
/* Animation for fading in and out the snackbar */
@-webkit-keyframes fadein {
  from {bottom: 0; opacity: 0;}
  to {bottom: 30px; opacity: 1;}
}
@keyframes fadein {
  from {bottom: 0; opacity: 0;}
  to {bottom: 30px; opacity: 1;}
}
@-webkit-keyframes fadeout {
  from {bottom: 30px; opacity: 1;}
  to {bottom: 0; opacity: 0;}
}
@keyframes fadeout {
  from {bottom: 30px; opacity: 1;}
  to {bottom: 0; opacity: 0;}
}

Step 3 - Add JavaScript:

Use JavaScript to add the "show" class to the snackbar container by clicking the button:

function myFunction() {
  // Get the snackbar DIV
  var x = document.getElementById("snackbar");
  // Add the "show" class to the DIV
  x.className = "show";
  // 3 seconds later, remove the "show" class from the DIV
  setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}

Try It Yourself