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

为何display:flex容器内的表单输入框宽度会缩短?

解决Flex布局下输入框宽度无法展开的问题

你的输入框设置了width:100%却无法展开,核心问题出在flex容器的子元素空间分配上:

  • .search-button作为flex容器,它的子元素.div-2-s1没有设置占据剩余空间的属性,导致.div-2-s1的宽度被内部内容撑开,输入框的100%只是相对于这个被限制的父容器,自然无法铺满可用区域。

修复方案

  1. 给.div-2-s1添加flex: 1,让它占据.search-button容器中除.div-1-s1之外的所有剩余空间
  2. 给表单form设置width: 100%; margin: 0;,消除表单默认边距并让它填满父容器
  3. 统一边框样式(可选),让整体组件的边框更贴合设计效果

修改后的完整代码

CSS 部分

.search-button {
  display: flex;
  justify-content: left;
  margin-left: .4em;
  margin-bottom: 1em;
  /* 统一组件边框,消除内部白边 */
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  overflow: hidden;
}

.div-1-s1 {
  font-family: 'Plus Jakarta Sans', sans-serif;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1.25rem;
  background-color: white;
  padding: .8em .7em .8em .75em;
  display: flex;
  justify-content: center;
  align-items: center;
  border: none;
}

.div-1-s1 img {
  padding-left: 0.6rem;
}

.div-2-s1 {
  display: flex;
  /* 关键:让容器占据剩余空间 */
  flex: 1;
}

.div-2-s1 form {
  width: 100%;
  margin: 0;
}

.div-2-s1 input {
  font-family: 'Plus Jakarta Sans', sans-serif;
  font-weight: 400;
  font-size: 0.875rem;
  padding: .8em 0 .8em .9em;
  border: none;
  line-height: 1.25rem;
  width: 100%;
  outline: none;
}

#sent-icon {
  padding: .7em .5em .7em .5em;
  background-color: white;
  border: none;
  margin-right: 0;
  cursor: pointer;
}

HTML 部分

<div class="search-button">
  <div class="div-1-s1">
    <span>All</span>
    <img src="t-icon.svg" alt="下拉图标" />
  </div>
  <div class="div-2-s1">
    <form action="#">
      <input type="text" id="label" placeholder="Search a location">
    </form>
    <img src="f2-icon.svg" alt="搜索图标" id="sent-icon" />
  </div>
</div>

关键说明

  • flex: 1 是 flex-grow:1; flex-shrink:1; flex-basis:0% 的简写,它会让元素在flex容器中自动填充剩余空间
  • 移除了各个子元素的白色边框,改用.search-button统一设置边框,避免组件内部出现多余的白边
  • 去掉输入框的默认轮廓,提升视觉体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 00:45:01