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

点击展开式搜索框输入文本内边距设置及溢出问题如何解决?

问题原因

默认CSS盒模型为content-box,元素的max-width仅统计内容区域宽度,内边距会额外叠加在总宽度之上。你给input新增20px左内边距后,展开后的input总宽度变为350px内容宽度 + 20px内边距 = 370px,超出了预期的350px宽度,因此出现溢出问题。
同时你现在的写法还存在隐藏问题:input初始状态max-width为0,但padding-left:20px始终存在,收起状态下会露出20px的输入框区域,不符合完全收起的交互预期。

解决方案

推荐使用以下修改方法,同时解决溢出和收起状态残留的问题:

  1. 给input添加box-sizing: border-box属性,让内边距被包含在宽度计算范围内
  2. 将padding-left的配置移到勾选展开的状态规则中,实现内边距随输入框同步过渡的效果

修改后的完整CSS代码如下:

.search {
  float: left;
  position: relative;
}

.search-box input {
  background: #F5B7B1;
  color: white;
  outline: none;
  border: none;
  height: 40px;
  width: 350px;
  max-width: 0px;
  -webkit-transition: all 0.5s 0s ease;
  -moz-transition: all 0.5s 0s ease;
  -o-transition: all 0.5s 0s ease;
  transition: all 0.5s 0s ease;
  box-sizing: border-box; /* 新增,修改盒模型 */
}

.search-box label {
  position: absolute;
  height: 30px;
  width: 40px;
  background-color: #E74C3C;
  text-align: center;
  padding-top: 12px
}

.search-box label i {
  cursor: pointer;
  color: white;
}

#check:checked ~ .search-box input{
  max-width: 350px;
  padding-left: 20px; /* 把padding移到展开状态 */
}

#check{
  display: none;
}

.search-box input::placeholder{
  color: #E5E7E9;
}

如果你不想修改盒模型,也可以直接调整展开后的最大宽度值,将#check:checked ~ .search-box input的max-width改为330px(扣减20px内边距的宽度)即可,同样建议把padding-left移到展开状态规则中,避免收起状态残留。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:27:03