angularangular-materialmaterial-design

How to handle elevation in Angular Material 18+?


According to the material 3 spec, different levels of elevation are supposed to be handled by color instead of shadow. However in my Angular Material 18 project, all backgrounds seem to have the same color/elevation (eg toolbar, navbar and cards). How is this supposed to work exactly? According to the docs (https://material.angular.io/guide/elevation) I am supposed to use classes, but they don't seem to be doing anything in version 18+. Any help would be greatly appreciated.

EDIT: https://m3.material.io/styles/elevation/overview


Solution

  • This seems to be a known P4 bug in angular material. It's still not fixed, it was raised for angular 15.

    bug(mat-card): mat-elevation-zx no longer working for mat-card after upgrade to version 15 - Github issue

    Do upvote that issue so that it gets fixed in the future.


    The reason you are getting this issue is that the theme styles are having more precedence than the elevation class that is why the box shadow does not get applied.

    As for the temporary workaround.

    All you need to do implement the temporary workaround by user GoodGuyGregory

    @for $i from 0 through 24 {
      .mat-mdc-card.mat-elevation-z#{$i} {
        @include mat.elevation($i);
      }
    }
    

    We recreate the elevation classes at the angular stylesheet level, so that the precedence issue is resolved.

    If for other angular material components, try the below fix, which I use !important to guarantee the override is applied.

    @for $i from 0 through 24 {
      .mat-elevation-z#{$i} {
        @include mat.elevation($i) !important;
      }
    }
    

    So the final output will be:

    @use '@angular/material' as mat;
    
    $theme: mat.define-theme(
      (
        color: (
          theme-type: light,
          primary: mat.$azure-palette,
          tertiary: mat.$blue-palette,
        ),
      )
    );
    
    body {
      @include mat.all-component-themes($theme);
      font-family: Roboto, 'Helvetica Neue', sans-serif;
      margin: 0;
      padding: 30px;
      height: 100%;
    }
    
    html {
      height: 100%;
    }
    
    @include mat.core();
    @include mat.color-variants-backwards-compatibility($theme);
    
    @for $i from 0 through 24 {
      .mat-mdc-card.mat-elevation-z#{$i} {
        @include mat.elevation($i);
      }
    }
    

    Stackblitz Demo

    Angular material elevation documentation