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

为何input元素超出div容器边界?调整字体大小后问题重现

解决Input元素超出容器边界的问题

你的问题根源在于两个点:

  1. 默认盒模型下,input的padding-left:5px会额外增加元素宽度,原本设置的150px宽度会变成155px
  2. input和button作为内联块元素,HTML代码中的换行被解析为空白字符,额外占用了容器空间
    两者叠加后,总宽度超过了.box-cep的245px,导致input溢出容器。

下面是修复后的完整代码:

CSS代码

.box-cep {
  width            : 245px;
  height           : 30px;
  margin-top       : 10px;
  margin-left      : 25px;
  border           : 2px solid black;
  font-size        : 0; /* 消除内联元素间的空白间距 */
}
.box-cep input {
  width            : 150px;
  height           : 30px;
  border           : none;
  box-sizing       : border-box; /* 让padding包含在宽度内 */
  font-size        : 14px; /* 恢复字体大小 */
}
.box-cep button {
  width            : 95px; /* 调整宽度匹配容器总宽度 */
  height           : 30px;
  border           : none;
  background-color : #FF7518;
  color            : white;
  font-family      : "Century Gothic";
  font-size        : 18px;
  font-weight      : bold;
  box-sizing       : border-box;
}
.cep-txt {
  font-family      : "Century Gothic";
  font-size        : 14px;
  padding-left     : 5px;
}

HTML代码

<div class="box-cep">
  <label for="">
    <input type="text" class="cep-txt" placeholder="Digite seu CEP..."><button>Calcular!</button>
  </label>
</div>

关键改动说明

  • box-sizing: border-box:强制元素的padding、border都包含在设置的width/height内,避免额外占用空间
  • .box-cep设置font-size:0:消除内联块元素之间的空白间距,也可以通过把input和button写在同一行的方式替代
  • 调整button宽度为95px:150px(input宽度)+95px(button宽度)=245px(容器宽度),刚好填满容器

问题原效果截图:
原效果截图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:30:56