简体   繁体   中英

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?

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>

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM