画面の途中でテキストの文字が変化するアニメーションの作成方法

CSS

画面の途中でテキストの文字が変化するアニメーションの作成方法を紹介します。

目次から読む

デモ

See the Pen
by Sosak (@Sosak2021)
on CodePen.

HTML

<section class="section-text-anim">
  <div class="div-text-anim">
    <h2 class="h2-text-anim">Lorem ipsum dolor sit amet consectetur adipisicing elit. A similique voluptates perspiciatis ullam obcaecati necessitatibus minus</h2>
  </div>
  <div class="div-text-anim">
    <h2 class="h2-text-anim">Lorem ipsum dolor sit amet consectetur adipisicing elit. A similique voluptates perspiciatis ullam obcaecati necessitatibus minus</h2>
  </div>

同じ文章を2つ用意します。

SCSS

.section-text-anim {
  position: relative;
  width: 100%;
  height: 100vh;
  display: flex;
  overflow: hidden;

  & .div-text-anim {
    position: relative;
    width: 50%;
    background: #2f5f6b;
    overflow: hidden;

    &:nth-child(1) {
      background: url('https://source.unsplash.com/random');
      background-size: cover;
      & .h2-text-anim {
        -webkit-text-stroke: 5px; //文字の枠線の太さ
        -webkit-text-stroke-color: #fff; //枠線の色
        // -webkit-text-fill-color: #fff; //文字の中の色
        -webkit-text-fill-color: transparent; //文字の中の色
        left: 100%; //これがないと違う文字が続いてしまう、100%で同じ位置からスタートできる
      }
    }


    & .h2-text-anim {
      font-size: 10em;
      line-height: 100vh;
      position: absolute;
      white-space: nowrap;
      line-height: 100vh;
      animation: animate 60s linear infinite;
    }
  }
}

@keyframes animate {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-100%);
  }
}

displayのflexで子要素を横並びにして、子要素は50%のwidthを設定します。
overflowはhiddenにしておきます。
そして、画像のあるようの文字色を変えたいので、-webkit-text-strokeを使います。
文字の枠線の太さを設定できます。
-webkit-text-stroke-colorで文字の輪郭の色を決められ、
-webkit-text-fill-colorで文字の中身の色を決定できます。transparentを使うことで、中身を透けさせることが可能です。
あとは、文字をはみ出すようにするため、white-spaceにnowrapを設定します。
あと重要な点として、文字の画像の方には、leftを100%設定することで、画像のない方と同じ位置からアニメーションをスタートさせることができます。
これを設定しないと違う文字が途中から表示されてしまいます。
それを、translateのXで移動させるアニメーションをつければ完成します。

CSS

Posted by devsakaso