MUI v5中如何让同一行不同元素高度一致并实现垂直对齐
MUI v5 同行元素高度对齐修复方案
问题原因
- Grid容器默认配置的
alignItems="center"为元素中心点对齐,TextField因携带label、helperText整体占位高度远大于Button,导致垂直错位 - Button默认高度未与TextField输入框高度匹配
具体修改步骤
- 移除
Mui.Box上的无效属性:sx={12}、md={12}属于Grid组件的断点配置,写在Box上不会生效可直接删除 - 将Grid容器的
alignItems属性值从center改为flex-end,让两个元素底部对齐 - 给Button添加
sx配置,固定高度与TextField输入框高度一致
修复后完整代码
<Mui.Box m={2} component="form" noValidate autoComplete="off" > <Mui.Card variant="outlined" raised sx={{ p: 2 }}> <Mui.Grid container spacing={2} direction="row" alignItems="flex-end" justifyContent="center"> <Mui.Grid item xs={12} md={3}> <Mui.TextField required fullWidth id="password" label="Password" type="password" defaultValue="" helperText="Some important text" /> </Mui.Grid> <Mui.Grid item xs={12} md={3}> <Mui.Button fullWidth variant="contained" size="large" sx={{ height: '56px' }} > Authenticate </Mui.Button> </Mui.Grid> </Mui.Grid> </Mui.Card> </Mui.Box>
可选优化
如果需要适配不同主题的尺寸规范,可以把高度值替换为MUI主题变量,避免硬编码:
sx={{ height: theme => theme.spacing(7) }}
如果不需要展示helperText,可给TextField添加配置隐藏辅助文本,再配合alignItems="center"也可实现对齐:
<TextField // 其他原有属性 FormHelperTextProps={{ sx: { display: 'none' } }} />
内容的提问来源于stack exchange,提问作者Bill Software Engineer
相关产品推荐
相关产品推荐

