表单布局用 Flex 还是 Grid 更合适?
我在写一个用户信息编辑表单,想让 label 和 input 左右对齐,但用 Flex 布局总感觉间距控制不好,试过 Grid 又担心兼容性。有没有更稳妥的方案?
目前代码是这样写的:
const UserInfoForm = () => (
<div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
<div style={{ display: 'flex', alignItems: 'center' }}>
<label style={{ width: '80px' }}>姓名</label>
<input style={{ flex: 1 }} />
</div>
<div style={{ display: 'flex', alignItems: 'center' }}>
<label style={{ width: '80px' }}>邮箱</label>
<input style={{ flex: 1 }} />
</div>
</div>
);
但输入框长度不一致时,label 对不齐,看着很乱,求指点!
直接上代码,把外层容器设为 Grid,两列布局:第一列固定宽度给 label,第二列自动伸缩给 input。
这样写,所有 label 都在同一列,宽度统一,input 也在同一列,长度也统一。维护起来也简单,想改 label 宽度只需要改
gridTemplateColumns一个地方,不用去遍历改样式。