Dext1232
Dext1232

Reputation: 253

Styling Material UI components using CSS

I have a Material UI component, and I am trying to custom style it using the CSS.

Following is the code:

<IconButton className="my-class">
    <Close />
</IconButton>

CSS:

.my-class {
  float: right;
  margin-left: auto;
  margin-right: 0;
}

But I am not able to style it, when I tried the following, it works:

<IconButton style={{ float: 'right', marginLeft: 'auto', marginRight: '0' }}> 
    <Close />
</IconButton>

Why I am not able to style the Material UI components using regular CSS?

Upvotes: 2

Views: 5697

Answers (3)

fatik
fatik

Reputation: 1

Use "sx" instead of "styles" in mui sx prop is used instead of styles

Upvotes: 0

hotcakedev
hotcakedev

Reputation: 2515

You can style MUI components using several ways like GlobalStyles API, sx, styled or even normal way.

If you are going to style the particular component like IconButton, and if you have a look at the document for the API, you can find the class names for the component.

Here's couple of references. https://mui.com/customization/how-to-customize/#main-content

How to give conditional style to MUI TextField?

Upvotes: 0

Nemanja
Nemanja

Reputation: 3679

Most CSS-in-JS solutions inject their styles at the bottom of the HTML <head>, which gives MUI precedence over your custom styles. You need to use the StyledEngineProvider exported from @mui/material/styles with the injectFirst option, in order for the CSS injection order to be correct. It is explained here.

So something like this shoud work:

<StyledEngineProvider injectFirst>
    <IconButton className="my-class">
      <CloseIcon></CloseIcon>
    </IconButton>
</StyledEngineProvider>

Upvotes: 6

Related Questions