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

CSS实现句子内单词切换异常:单词被句子遮挡问题求助

问题:单词切换动画导致文本错位

我用以下Slim代码构建句子,希望实现中间的单词(Explore/Engage/Conquer/Defeat)自然切换显示,比如显示为「Log in to Conquer the members of the outer realm」,但当前CSS代码让单词跑到了句子后方。

Slim代码

p 
  | Log in to 
  span.word-shapeshift.text-center
    span.word Explore
    span.word Engage
    span.word Conquer
    span.word Defeat 
  | the members of the outer realm

CSS(SCSS)代码

$speed: 12s;
$wordCount: 4;

.word-shapeshift {
  color: #ecf0f1;  
  white-space: nowrap;
  position: relative;
  color: #fff;
  filter: contrast(25) blur(1px);

  .word {
    position: absolute;
    display: inline-block;
    top: 50%; left: 50%;
    transform: translate(-50%, -50%);
    animation: rotateWord $speed infinite ease-in-out;
  
    @for $i from 0 to $wordCount {
      &:nth-child(#{$i + 1}) {
        animation-delay: ($speed / ($wordCount + 1) * $i) - $speed;
      }
    }
  
    @keyframes rotateWord {
      0%, 5%, 100% { filter: blur(0px); opacity: 1; }        
      20%, 80% { filter: blur(1em); opacity: 0; }        
    }
  }
}

问题原因及修复方案

错误核心

.word-shapeshift设置了position: relative但默认是块级元素(display: block),同时内部的.word用了绝对定位脱离正常文档流,导致:

  1. .word-shapeshift高度塌陷、宽度为0,前后文本直接拼接在一起
  2. 绝对定位的单词相对于宽度为0的父容器居中,最终跑到整个句子后方

修复步骤

  1. 给.word-shapeshift添加display: inline-block,让它和前后文本在同一行布局,同时能容纳内部绝对定位元素
  2. 给.word-shapeshift设置固定宽度(根据最长单词的宽度调整,比如width: 90px),避免容器宽度变化影响整体句子布局
  3. 给.word-shapeshift设置合适高度,确保单词垂直居中时不会溢出容器

修改后的SCSS代码

$speed: 12s;
$wordCount: 4;

.word-shapeshift {
  color: #ecf0f1;  
  white-space: nowrap;
  position: relative;
  color: #fff;
  filter: contrast(25) blur(1px);
  // 新增:让容器和文本同行,设置固定宽高
  display: inline-block;
  width: 90px;
  height: 1.2em;

  .word {
    position: absolute;
    display: inline-block;
    top: 50%; 
    left: 50%;
    transform: translate(-50%, -50%);
    animation: rotateWord $speed infinite ease-in-out;
  
    @for $i from 0 to $wordCount {
      &:nth-child(#{$i + 1}) {
        animation-delay: ($speed / ($wordCount + 1) * $i) - $speed;
      }
    }
  
    @keyframes rotateWord {
      0%, 5%, 100% { filter: blur(0px); opacity: 1; }        
      20%, 80% { filter: blur(1em); opacity: 0; }        
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 01:07:32