如何通过createTheme默认移除MUI Input紧跟Label后的上边距
解决方案
- 你要修改的是
FormControl组件的样式——MUI里<label>紧跟Input的布局间距逻辑由它控制,通过createTheme全局覆盖对应样式即可:
import { createTheme, ThemeProvider } from '@mui/material/styles'; import FormControl from '@mui/material/FormControl'; import InputLabel from '@mui/material/InputLabel'; import Input from '@mui/material/Input'; const theme = createTheme({ components: { MuiFormControl: { styleOverrides: { // 覆盖默认的间距规则 marginNormal: { '&:not(:first-child)': { marginTop: 0, }, }, // 同步修改紧凑模式下的间距 marginDense: { marginTop: 0, }, // 或者直接指定内部Input的上边距 root: { '& .MuiInputBase-root': { marginTop: 0, }, }, }, }, }, }); // 用ThemeProvider包裹应用组件生效 function App() { return ( <ThemeProvider theme={theme}> <FormControl> <InputLabel>用户名</InputLabel> <Input /> </FormControl> </ThemeProvider> ); }
- 补充说明:你截图里的CSS是MUI默认给
FormControl添加的间距规则,通过上述方式修改MuiFormControl的styleOverrides,就能全局把所有紧跟Label的Input上边距设为0。
内容的提问来源于stack exchange,提问作者E C I N
相关产品推荐
相关产品推荐

