angularsassangular-material

Angular Material 18: how to change background color?


I think it's a very common problem, though I was not able to find a solution.

I have a dark and a light theme defined such as:

styles.scss

@use "@angular/material" as mat;

// Include the common styles for Angular Material.
@include mat.core();

// Define the theme object.
$light-theme: mat.define-theme(
  (
    color: (
      theme-type: light,
      primary: mat.$azure-palette,
      tertiary: mat.$blue-palette,
    ),
    density: (
      scale: -5,
    ),
  )
);

$dark-theme: mat.define-theme(
  (
    color: (
      theme-type: dark,
      primary: mat.$azure-palette,
      tertiary: mat.$blue-palette,
    ),
    density: (
      scale: -5,
    ),
  )
);

// Include theme styles for core and each component used in your app.
html,
body {
  @include mat.all-component-themes($light-theme);

  .dark-theme {
    // This mixin only generates the color styles now.
    @include mat.all-component-colors($dark-theme);
  }

  height: 100%;
}

body {
  margin: 0;
  font-family: Roboto, "Helvetica Neue", sans-serif;
}

how to change background color of Angular Material Components with one color for light and one color for dark theme? (it is plain black for ligth theme, and plain white for dark theme by default)


Solution

  • Add the mat-app-background class to your <body> element in index.html (see the docs):

    <body class="mat-app-background">
      <!-- content -->
    </body>
    

    This will apply the default background colors #fafafa in light theme and #303030 in dark theme. If you want to override those colors, you can set a new value for the --mat-app-background-color variable in your styles.scss:

    body {
      --mat-app-background-color: #eee;
      
      .dark-theme {
        --mat-app-background-color: #111;
      }
    }
    

    To override the background colors of the components, you can set values for their respective CSS variables:

    body {
      --mdc-outlined-card-outline-color: #eee;
      --mat-table-background-color: #eee;
      // this is not a complete list, add more variables as needed
    }
    

    I strongly advice against using always the same background color for all Material components, they intentionally have different background colors to visually separate them.