You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript/Tailwind CSS:表单输入框右侧对齐按钮的布局问题

解决方案:让输入框填满容器并与按钮并排

问题出在flex布局的子项默认不会自动占据剩余空间,只需要给输入框所在的容器添加flex-grow-1类,就能让它填满按钮之外的所有可用宽度:

修改后的代码如下:

<div id='requestClients'>
  <Label>Client(s)</Label>
  {fields.map((field,index) => (
    <div key={index} className='flex pt-1 gap-1'>
      <FormField
        control={requestForm.control}
        key={field.id}
        name={`clients.${index}.value`}
        render={({field}) => (
          {/* 添加 flex-grow-1 让输入框容器占据剩余空间 */}
          <FormItem className='flex-grow-1'>
            <FormControl>
              {/* 确保输入框宽度100%(多数UI库默认已设置,若未生效可加 w-full) */}
              <Input placeholder='Email' required {...field} className='w-full'/>
            </FormControl>
            <FormMessage/>
          </FormItem>
        )}
      />
      {fields.length-1 === index && fields.length < 10 && (
        <Button type='button' onClick={() => append({value:''})}><Plus/></Button>
      )}
      {fields.length-1 != index && fields.length > 1 && (
        <Button type='button' onClick={() => remove(index)}><X/></Button>
      )}
    </div>
  ))}
</div>

关键说明:

  • flex-grow-1 作用于FormItem,让它在flex布局中优先占据容器的剩余空间,按钮则保持自身宽度
  • 给Input添加w-full是为了确保输入框填满FormItem的宽度(部分UI组件库的Input可能默认已是100%宽度,可根据实际情况调整)
  • 原flex容器的gap-1保持按钮和输入框之间的间距,布局更美观

内容的提问来源于stack exchange,提问作者Skuldakn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 05:33:16