Search code examples
cssangularangular-material2

Angular Material Overriding Default Style of SnackBar Component


I am attempting to override the default max-width of the snackbar component in Angular Material.

The CSS applied by Angular Material is shown below:

.mat-snack-bar-container {
    border-radius: 2px;
    box-sizing: border-box;
    display: block;
    margin: 24px;
    max-width: 568px;
    min-width: 288px;
    padding: 14px 24px;
    transform: translateY(100%) translateY(24px);
}

I have tried overriding using the same style in my style.css file but this style is overridden by the default style.

 .mat-snack-bar-container {
   max-width: 800px;
 }

I have found an answer to a similar question but I know the answer to that question is now deprecated (/deep/ is deprecated).

Is there a best practices solution to this?


Solution

  • To do this properly, you need to set the View Encapsulation to None on your component:

    @Component({
        templateUrl: './my.component.html' ,
        styleUrls: ['./my.component.css'], 
        encapsulation: ViewEncapsulation.None,
    })
    

    Then in your component css you can just do this:

    .mat-snack-bar-container {
       max-width: 800px;
    }
    

    From the official docs:

    View Encapsulation = None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.