Override css styles in react js

I created an application in react js using the ant design library. In my css file I added some base styles:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

I expect that these styles should override all styles, but they dont override antd styles. Inspecting the p tag in the console I noticed that this styles:

 {
    margin-top: 0;
    margin-bottom: 1em;
} /// comes from antd.css

overide my previous styles. How to fix this (to make my styles to override all styles) without using !important? and I have also gone through so many blogs on CSS vs JavaScript.

demo: https://codesandbox.io/s/antd-create-react-app-forked-0vs14?file=/index.js:315-811

The * selector doesn’t hold a lot of specificity, so it is unlikely to override many other selectors.

2 Likes

That rule will only over-ride rules of less specificity or rules of the same specificity that appear earlier in the stylesheet. It is generally used to remove the UA (browser) defaults rather than for setting anything important.

You could add more specificity to the rule like this.

body * {
  margin: 0;
  padding: 0;
}

That would override the p styles you were seeing but means that anywhere you wanted to add a margin or padding you would have to match the specificity again.

e.g.

body div{margin:1rem}

That would soon become unmanageable and not a good thing to do.

The best thing to do is to set some defaults for the elements you want to style by context and give them more weight than the ‘ant’ styles.

Maybe

body p {
    margin: 0;
  padding: 0;
}

In the end though you just have to manage each element on a case by case basis as setting !important would also be unmanageable unless it was just a one off case.

2 Likes