Blog>
Snippets

Theming Angular Material with CSS Variables

Explain how to customize Angular Material components using CSS variables, illustrating how to override default theming and set a custom color palette.
/* Define CSS variables in a global stylesheet */
:root {
  --primary-color: #1976d2;
  --accent-color: #e91e63;
  --warn-color: #f44336;
}

/* Apply CSS variables to Angular Material components */
.mat-toolbar {
  background-color: var(--primary-color);
}

.mat-fab, .mat-mini-fab {
  background-color: var(--accent-color);
}

.mat-warn {
  color: var(--warn-color);
}
This snippet defines a set of CSS variables for primary, accent, and warn colors at the root level, then applies these variables to various Angular Material components. The `.mat-toolbar` class's background is changed to the primary color, floating action buttons (`.mat-fab` and `.mat-mini-fab`) get the accent color, and any element with the `.mat-warn` class is styled with the warn color. These changes will override default theming for Angular Material components.
/* Angular module file where you include Angular Material */
import { NgModule } from '@angular/core';
import { MatToolbarModule } from '@angular/material/toolbar';

@NgModule({
  imports: [
    MatToolbarModule,
    // ... other Angular Material modules
  ],
  // ...
})
export class MaterialModule {}
This is a typical Angular module where you might include various Angular Material modules such as MatToolbarModule. This module imports and makes available these components throughout your application, which can then be styled using the CSS variables defined earlier.
/* Add a component-specific stylesheet if needed */
@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css'],
  // might also include encapsulation or other component metadata
})
export class MyComponent { /* ... */ }
Here is an Angular component definition that might use styled Angular Material components. It points to a component-specific stylesheet where you can further customize Material components for this component only, using the same CSS variables or adding new overrides.