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

CSS问题:输入框聚焦后整体右移5%,translateX(-5%)效果不佳

问题原因与解决方法

问题根源

你遇到的输入框聚焦后向右偏移的问题,本质是居中方式和宽度变化的冲突:

  • 输入框原本靠margin: 20px auto实现居中,左右margin会根据父容器宽度和自身宽度自动计算;
  • 聚焦时输入框宽度从220px涨到270px,左右margin会从(300-220)/2=40px骤降到(300-270)/2=15px,左边margin减少了25px,导致输入框相对于原位置向右偏移;
  • 你尝试的translateX(-5%)无效,是因为这个百分比基于输入框自身宽度(270px的5%仅13.5px),不足以抵消25px的位移,而且偏移基准和margin变化的逻辑不匹配。

修复方案

推荐修改输入框的居中方式,用position + transform替代margin:auto,这样无论宽度怎么变,输入框都会始终保持居中:

修改后的CSS代码:

.box {
  position: absolute;
  width: 300px;
  padding: 30px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgb(0, 0, 0, 0.4);
  text-align: center;
  border-radius: 24px;
}

.box input[type="text"],
.box input[type="password"] {
  border: 0;
  background: none;
  display: block;
  /* 替换margin:auto为相对定位+transform居中 */
  margin: 20px 0;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  border: 3px solid rgb(50, 92, 221);
  padding: 14px 10px;
  width: 220px;
  outline: none;
  color: white;
  border-radius: 24px;
  transition: 1s;
}

.box input[type="text"]:focus,
.box input[type="password"]:focus {
  width: 270px;
  border-color: rgb(242, 175, 62);
}

方案原理

left: 50%让输入框左侧对齐父容器的水平中线,transform: translateX(-50%)再把输入框向左偏移自身宽度的一半,最终实现完美居中。这种居中方式不受输入框宽度变化影响,宽度增加时,translateX(-50%)会自动根据新宽度调整偏移量,彻底解决偏移问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 03:36:21