I am using Angular 16 with Angular Material UI components in my project, and I want to apply custom styles like rounded corners, double-bordered inputs, custom fonts, etc. I have achieved this by overriding the Material CSS classes using !important
, but I am unsure if this is the best practice.
Here's an example of how I am overriding the CSS classes:
.mat-form-field {
border-radius: 8px !important;
border: 2px solid #000 !important;
}
I have a few questions:
Is overriding Material UI classes using !important
recommended? Could this lead to potential issues like breaking styles in future updates or causing unexpected behavior?
Using Mixins: I've come across suggestions to use mixins instead of !important
to apply custom styles. Where can I find the appropriate Angular Material mixins for this, and could you provide an example of how to use them to avoid these issues?
Any guidance on best practices for globally customizing Angular Material components would be greatly appreciated. Thanks!
It is not good practice to override the Angular Material Styles by targeting their element's selectors, with and without !important
. The reason is that Angular Material does not ensure that those selectors stay the same, see the docs. They might do refactorings or renamings, which can easily lead to your styles having no effect anymore. Instead, you should provide new values for their CSS variables, if possible. For example, to change the border radius of the form field, add the following CSS to your styles.css
:
:root {
--mdc-filled-text-field-container-shape: 8px;
}
To find out which CSS variables they use, you can inspect the DOM with the DevTools of your browser.
With Angular Material v19 (currently in RC), the new recommendation is to use the new overrides SCSS mixins. Also starting from v19, the docs contain a new "Styling" tab where you can see which tokens you can override. For example, for the form field, you can now override the styles like the following:
@use '@angular/material' as mat;
:root {
@include mat.form-field-overrides((
filled-container-shape: 8px;
));
}