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

技术问询:如何将中间textbox在div中居中并让icon贴近textbox

解决方案:实现中间输入框居中+图标贴近对应输入框

嘿,我来帮你搞定这个布局需求!首先先修正原代码里的两个小问题:一是有重复的id="box"(ID必须唯一,不然后续JS操作容易出bug),二是多了一个多余的</span>标签。接下来用Flexbox布局就能轻松实现你要的效果,话不多说,直接看修改后的代码:

修改后的HTML代码

<div class="card">
  <div class="col-md-12 input-container">
    <span class="input-wrapper">
      <input type="text" name="left-box" id="left-box" style="width:50px;">
      <i class="fa fa-long-arrow-left" style="font-size:36px;vertical-align:-19%;color:green"></i>
    </span>
    
    <span class="middle-input-wrapper">
      <input type="text" name="boxx" id="boxx" style="width:200px;">
    </span>
    
    <span class="input-wrapper">
      <i class="fa fa-long-arrow-right" style="font-size:48px;color:green"></i>
      <input type="text" name="right-box" id="right-box" style="width:50px;">
    </span>
  </div>
</div>

对应的CSS代码

.input-container {
  display: flex;
  justify-content: center; /* 让所有子元素整体水平居中 */
  align-items: center; /* 垂直居中,让图标和输入框对齐更协调 */
  gap: 1rem; /* 控制中间输入框和两侧元素的间距,可按需调整大小 */
}

.input-wrapper {
  display: flex;
  align-items: center;
  gap: 0.25rem; /* 让图标和对应的输入框紧紧贴近,这个值可以根据视觉效果微调 */
}

效果说明

  1. 父容器input-container用Flex布局的justify-content: center直接实现了中间输入框的水平居中,align-items: center让所有元素垂直对齐更美观;
  2. 把图标和对应输入框放进同一个input-wrapper,用Flex布局+小间距gap,完美实现图标贴近输入框的要求;
  3. 移除了原代码里多余的浮动和margin,用Flex的gap控制间距,布局更稳定、易维护;
  4. 修正了重复ID的问题,避免后续交互逻辑出问题。

如果你的项目里已经引入了Bootstrap(因为用到了col-md-12),这个方案也完全兼容,不会有冲突哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:57:44