Overwrite angular material css -- Why does !important work

Viewed 555

I'm trying to overwrite the css of some angular material components. I read about /deep/ and :ng-deep no longer being used and so I was trying to add some code in styles.css. The only thing I'm able to do is add new properties to the class, not overwrite the ones that are already there.

background-color changed ok

padding didn't change at all

Can you help me to overwrite this css?

---Update--- So I managed to change the padding using !important:

Use of !important to change padding

I would like to know if there is a better way of doing this and also why does it work?

1 Answers

The MDN Web Docs has a great explanation of CSS specificity and the role of !important in overriding the cascade. Keep in mind that id="" is more specific than class="".

https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

From the docs:

Some rules of thumb:

Always look for a way to use specificity before even considering !important

Only use !important on page-specific CSS that overrides foreign CSS

Never use !important on site-wide CSS.

Instead of using !important, consider:

Make better use of the CSS cascade, Use more specific rules.

Indicate one or more elements before the element you're selecting, the rule becomes more specific and gets higher priority.

IMHO your use of !important here is valid as you are overriding "external" css.

As for styling Angular Material Components, when you set up your project you are using either a pre-built or custom theme. If you have lots of customizations to make, a custom theme is the way to go.

Angular Material Theming

Related