How to Change the Position of a Mat Snackbar in Angular?

To change the position of a mat snackbar you can use the horizontalPosition and verticalPosition configuration options. The horizontalPosition controls the horizontal positioning while the verticalPosition controls the vertical positioning of the snackbar.

These are the set of values that these two options accept:

  • horizontalPosition – ‘start’ , ‘center’ , ‘end’ , ‘left’ and ‘right’
  • verticalPosition – ‘top’ , ‘bottom’

The default values of these two options are ‘center’ and ‘bottom’. That is why the snackbar is positioned at the center of the bottom line by default.

By using different combinations of these values you can position the snackbar at any desired position.

In the following example, we have set the horizontalPosition to ‘right’ and the verticalPosition to ‘top’, therefore the snackbar pops up in the top right corner of the screeen:

// Opens the snackbar in the top right corner
this.snackbar.open(message, action, {
  duration: 3000,
  horizontalPosition: 'right',
  verticalPosition: 'top'
});

Similarly, to position the snackbar in the bottom left corner you have to set the horizontalPosition to ‘left’ and the verticalPosition to ‘bottom’:

// Opens the snackbar in the bottom left corner
this.snackbar.open(message, action, {
  duration: 3000,
  horizontalPosition: 'left',
  verticalPosition: 'bottom'
});

Set Custom Position using the Panel Class

Using the horizontalPosition and verticalPosition configuration options you can only position the snackbar at some predefined positions.

But, with the help of a panel class and a little CSS, you can position the snackbar at any custom position you want.

Let’s first add a custom panel class 'my-snackbar' in the configuration object:

this.snackbar.open(message, action, {
  duration: 3000,
  panelClass: 'my-snackbar'  // <- Custom panel class
});

Next, open up your global styles.css file, specify the 'my-snackbar' class and use the top, bottom, left and right properties to control the position of the snackbar:

/* Add the following styles in global styles.css file */

.my-snackbar{
    margin: 0 !important;
    position: absolute;
    top: 200px;
    left: 300px;
}
/* opens the snackbar 200px from top and 300px from left */

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.