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

过渡兄弟元素宽度时如何防止文本移位

解决“Learn More”按钮悬停时文本移位/换行问题

我正在开发一个网站,需要实现一款分为两部分的“Learn More”按钮:左侧显示“Learn More”,右侧显示“+”。鼠标悬停时,左侧部分宽度收缩至0,右侧“+”部分展开占据整个按钮空间。目前用CSS宽度过渡实现动画,但左侧宽度缩小时文本会移位、换行,希望文本保持原位,被右侧元素遮挡而非换行,同时想了解更简便的实现方式。

原代码

CSS

.button-container {
  height: 4vw;
  width: 19vw;
  display: flex;
  align-items: center;
  padding: 0;
  border: none;
  cursor: pointer;
}

.button {
  height: 4vw;
  align-content: center;
  font-family: "Comfortaa", cursive;
  transition-duration: 0.6s;
  transition-property: width;
  transition-timing-function: ease-in-out;
}

.button-label {
  width: 15vw;
  background: #07BEB8;
  color: #FFF;
  font-size: 1.3vw;
  overflow: hidden;
}

.button-symbol {
  width: 4vw;
  background: #3DCCC7;
  color: #FFF;
  border-left: solid #FFF;
  font-size: 1.6vw;
  font-weight: bold;
}

.button-container:hover .button-label {
  width: 0;
}

.button-container:hover .button-symbol {
  width: 19vw;
}

HTML

<button class="button-container">
  <div class="button button-label">Learn More</div>
  <div class="button button-symbol">+</div>
</button>

解决方案

核心是阻止文本换行并保持居中,同时用flex布局简化宽度控制,避免硬编码固定尺寸:

修改后的代码

CSS
.button-container {
  height: 4vw;
  width: 19vw;
  display: flex;
  padding: 0;
  border: none;
  cursor: pointer;
  overflow: hidden; /* 隐藏子元素超出部分 */
}

.button {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center; /* 内容水平居中 */
  font-family: "Comfortaa", cursive;
  transition: flex 0.6s ease-in-out; /* 改用flex属性过渡,更灵活 */
}

.button-label {
  flex: 15; /* 初始占15份空间 */
  background: #07BEB8;
  color: #FFF;
  font-size: 1.3vw;
  white-space: nowrap; /* 强制文本不换行 */
  overflow: hidden;
}

.button-symbol {
  flex: 4; /* 初始占4份空间 */
  background: #3DCCC7;
  color: #FFF;
  border-left: solid #FFF;
  font-size: 1.6vw;
  font-weight: bold;
}

.button-container:hover .button-label {
  flex: 0; /* 悬停时完全收缩 */
}

.button-container:hover .button-symbol {
  flex: 1; /* 悬停时占据全部空间 */
}
HTML(无需修改)
<button class="button-container">
  <div class="button button-label">Learn More</div>
  <div class="button button-symbol">+</div>
</button>

关键修改说明

  • white-space: nowrap:强制“Learn More”文本不换行,避免宽度缩小时出现折行。
  • display: flex + justify-content: center:让文本始终保持居中,宽度收缩时不会移位。
  • 改用flex属性过渡:用占比代替固定vw宽度,布局更灵活,适配不同尺寸场景。
  • overflow: hidden:确保按钮容器能隐藏收缩时的超出内容,保证视觉效果整洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 19:52:17