Using Material-UI(React) Button with CSS, "select all immediate children" doesn't seem to work

Viewed 702

Given HTML :

<div className="button-container">
  <Button variant="contained">
        Default
  </Button>
  <Button variant="contained" color="primary">
        Primary
  </Button>
  <Button variant="contained" color="secondary">
        Secondary
  </Button>
</div>

I tried to apply a margin to all immediate children of button-container. But that didn't work.

.button-container > *{
    margin: 8px;
}

But this worked.

.button-container > Button{
    margin: 8px;
}

Is this problem with my syntax or compatibility issue when using JSX/React?

2 Answers
.button-container > *{
    margin: 8px;
}

The above code selects all the children of button-container class. So, it will select all the buttons and apply the given CSS.

.button-container > Button{
    margin: 8px;
}

The above code selects all the children of button-container class that have tag name as Button.

In either case, the output should apply the CSS as expected. In the first case, it might probably have something to do with selector specificity. Maybe try using !important and see if it works. Check out the codesandbox link below -

Edit Material demo

Another way to do it without using !important (which should be avoided as much as possible- read more here ) would be by begin more specific in you CSS selector. For eg. if you have the root div element with id - #root, you could mention the CSS as -

#root .button-container > * {
  margin: 30px;
}

In, your case, you CSS is probably getting overridden by another selector. By begin more specific, you increase the specificity of your selector which increases its precedence over other. You can learn more on how CSS specificity works here

Your selector is too "generic" so it is overriden by another selector. One quick (and dirty) way to fix it is by using !important but in general it is a good practice to avoid it.

Check this link for intstructions regarding !important as Stephen P posted in his comment.

Related