Material UI Button内边距无法调整,设置px属性无效果求助
问题分析
你遇到的情况是因为Material UI的secondary变体Button自带了优先级更高的水平内边距样式,直接用px简写或者同时设置paddingLeft/paddingRight时,自定义样式会被组件默认样式覆盖。单独设置其中一个属性时,刚好自定义样式优先级超过了默认的单属性规则,所以能生效。
可行解决方案
1. 强制覆盖默认样式(快速临时解决)
给内边距属性加上!important,强制让自定义样式优先级最高:
<Button variant='secondary' sx={{ fontSize: '0.9rem', fontWeight: 500, m: '1rem', paddingLeft: '0.1rem !important', paddingRight: '0.1rem !important', outline: 'none', '&:focus': { outline: 'none', }, }} > enable notifications </Button>
2. 针对Button内部标签元素设置内边距
Button的文本内容通常包裹在.MuiButton-label类的元素里,直接给这个内部元素设置内边距可以绕过组件的默认样式限制:
<Button variant='secondary' sx={{ fontSize: '0.9rem', fontWeight: 500, m: '1rem', outline: 'none', '& .MuiButton-label': { px: '0.1rem', }, '&:focus': { outline: 'none', }, }} > enable notifications </Button>
3. 全局修改Theme配置(适合多个Button需要统一样式的场景)
如果项目里多个secondary变体Button都需要这个内边距,可以在全局Theme里配置,一劳永逸:
import { createTheme, ThemeProvider } from '@mui/material/styles'; const theme = createTheme({ components: { MuiButton: { variants: [ { props: { variant: 'secondary' }, style: { paddingLeft: '0.1rem', paddingRight: '0.1rem', }, }, ], }, }, }); // 在根组件包裹ThemeProvider function App() { return ( <ThemeProvider theme={theme}> {/* 你的其他组件 */} <Button variant='secondary'>enable notifications</Button> </ThemeProvider> ); }
内容的提问来源于stack exchange,提问作者pauk
相关产品推荐
相关产品推荐

