[英]Styling Material UI components using CSS
I have a Material UI component, and I am trying to custom style it using the CSS.我有一个 Material UI 组件,我正在尝试使用 CSS 自定义样式。
Following is the code:以下是代码:
<IconButton className="my-class">
<Close />
</IconButton>
CSS: 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?为什么我无法使用常规 CSS 来设置 Material UI 组件的样式?
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.大多数 CSS-in-JS 解决方案在 HTML
<head>
的底部注入它们的 styles,这使 MUI 优先于您的自定义 styles。您需要使用从@mui/material/styles
导出的StyledEngineProvider
和injectFirst
选项,以便CSS 注入顺序是正确的。 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.您可以使用多种方式设置 MUI 组件的样式,例如GlobalStyles API 、 sx 、样式化甚至正常方式。
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.如果您要为 IconButton 等特定组件设置样式,并且查看 API 的文档,您可以找到该组件的 class 名称。
Here's couple of references.这里有几个参考。https://mui.com/customization/how-to-customize/#main-content
https://mui.com/customization/how-to-customize/#main-content
How to give conditional style to MUI TextField? 如何为 MUI TextField 提供条件样式?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.