如何在Material UI Grid水平布局中实现InputLabel文本垂直居中
不需要使用Paper等中间组件,借助MUI Grid自带的flex布局属性和组件样式覆盖即可实现需求,具体操作如下:
1. 调整Grid容器的垂直对齐规则
你封装的ContainerItem是Grid container类型,默认交叉轴对齐方式为stretch,只要给它添加alignItems="center"属性,就能让内部所有Grid Item在垂直方向居中对齐:
// 方式1:修改封装组件的默认属性,全局生效 const ContainerItem = (props) => <Grid container item alignItems="center" {...props} />; // 方式2:仅给需要的容器单独添加属性,局部生效 <ContainerItem alignItems="center"> {/* 内部标签、输入框组件 */} </ContainerItem>
2. 清除InputLabel默认的多余margin-bottom
InputLabel默认携带适配FormControl场景的底部margin,直接覆盖该样式即可,推荐两种实现方式:
- 方式一:使用sx属性临时覆盖,适合少量使用的场景
<InputLabel htmlFor="m_gen_ref_serie" sx={{ marginBottom: 0, lineHeight: '32px' }} > Serie </InputLabel>
其中lineHeight可以设置为和当前Input组件高度一致的值,进一步保证文本完全居中。
- 方式二:封装公共样式组件,适合大量复用的场景
import { styled } from '@mui/material/styles'; import InputLabel from '@mui/material/InputLabel'; const FormInputLabel = styled(InputLabel)(() => ({ marginBottom: 0, lineHeight: '32px' })); // 使用时直接替换原有InputLabel <FormInputLabel htmlFor="m_gen_ref_serie">Serie</FormInputLabel>
如果需要更稳妥的适配,也可以给包裹InputLabel的Grid Item添加对齐属性,让每个Item内部的元素单独垂直居中:
const Item = (props) => <Grid item xs={1} display="flex" alignItems="center" {...props} />;
内容的提问来源于stack exchange,提问作者TomR
相关产品推荐
相关产品推荐

