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

按钮文本CSS动画实现求助:图片无动画,文本从左至右平滑出现

实现按钮文本从左至右平滑出现的CSS动画

需求:按钮包含<img>标签与文本,页面加载时图片无动画直接显示,按钮文本从左至右平滑出现。

你之前尝试的方案问题分析

第一个方案

.my-anim{
    animation: btnslide .5s ease-out;
}
.my-anim::before {
    content: '';
    transform: translate(-50%, -50%);
    opacity: 0;
    transition: all .3s ease-in-out;
}

@keyframes btnslide {
    0%,25% {
        transform: translateX(-120%);
        opacity: 0;
    }
}
  • ::before伪元素未实际参与动画,属于冗余代码。
  • 动画未设置animation-fill-mode: forwards,动画结束后文本会自动回到初始位置,无法保持显示状态。
  • 未限制文本容器的溢出范围,动画开始前文本会显示在按钮左侧外部,破坏页面初始布局。

第二个方案

.myanim {
    display: inline-block;
    white-space: nowrap;
    overflow: hidden;
    animation: animslide 1s ease;
}
.myanim::before{
    width: 0%;
}

@keyframes animslide {
    from {
        width: 0%;
    }
    to {
        width: 100%;
    }
}
<button>
<img src="https://png.pngtree.com/element_our/20190530/ourmid/pngtree-correct-icon-image_1267804.jpg" height="20">
<span class="myanim">Hi there</span>
</button>
  • 初始状态未给.myanim设置width: 0%,动画启动时容器已处于文本的实际宽度,无法触发宽度从0到100%的变化。
  • 通过改变容器宽度实现的是文本“拉伸”效果,并非需求中的“平滑平移”入场动画。

正确实现方案

HTML结构

<button>
  <img src="https://png.pngtree.com/element_our/20190530/ourmid/pngtree-correct-icon-image_1267804.jpg" height="20">
  <span class="btn-text-wrapper">
    <span class="btn-text">Hi there</span>
  </span>
</button>

CSS代码

/* 可选:给按钮添加基础样式,优化布局 */
button {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: #f5f5f5;
  cursor: pointer;
}

/* 文本外层容器:限制溢出,确保文本滑动时不会超出范围 */
.btn-text-wrapper {
  display: inline-block;
  overflow: hidden;
}

/* 文本元素:承载平移动画 */
.btn-text {
  display: inline-block;
  /* 动画设置:从左外滑入,持续0.5秒,缓出效果,结束后保持最终状态 */
  animation: slideIn 0.5s ease-out forwards;
}

/* 定义平移动画 */
@keyframes slideIn {
  0% {
    transform: translateX(-100%);
    opacity: 0;
  }
  100% {
    transform: translateX(0);
    opacity: 1;
  }
}

方案说明

  • 采用两层嵌套结构:外层btn-text-wrapper设置overflow: hidden,将文本的滑动范围限制在容器内;内层btn-text作为动画载体,通过translateX实现从左至右的平滑平移。
  • 动画添加forwards属性,确保动画结束后文本保持最终显示状态,不会回弹。
  • 图片未添加任何动画规则,页面加载时直接显示,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:37:07