LoginSignup
0
0

More than 3 years have passed since last update.

背景色によって文字色が変わる、流れる文字のCSSアニメーション実現方法

Posted at

はじめに

こんな感じのを実現するためのコードです。
slider-demo.gif

コード

index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <title>流れる単語</title>
    <link rel="stylesheet" href="./index.css" />
  </head>
  <body>
    <div class="color-area">
      <div class="scroll-string scroll-string-white">流れる単語</div>
    </div>
    <div class="scroll-string scroll-string-blue">流れる単語</div>
  </body>
</html>
index.css
html {
  height: 100%;
}
body {
  height: 100%;
}
.color-area {
  width: 100%;
  height: 200px;
  top: 100px;
  position: relative;
  overflow: hidden;
  background-color: darkblue;
  z-index: 2;
}
.scroll-string {
  font-size: 30px;
  visibility: hidden;
  text-align: center;
  height: 50px;
  width: 100%;
  position: absolute;
  left: 0;
  right: 0;
  margin: auto;
}
.scroll-string-white {
  color: white;
  top: 0;
  animation: scroll-white 5s linear 0s 1 forwards;
  -webkit-animation: scroll-white 5s linear 0s 1 forwards;
  z-index: 3;
}
.scroll-string-blue {
  color: darkblue;
  top: 100;
  animation: scroll-blue 5s linear 0s 1 forwards;
  -webkit-animation: scroll-blue 5s linear 0s 1 forwards;
  z-index: 1;
}
@keyframes scroll-white {
  0% {
    transform: translateY(-100px);
    visibility: visible;
  }
  100% {
    transform: translateY(300px);
  }
}
@keyframes scroll-blue {
  0% {
    transform: translateY(-200px);
    visibility: visible;
    opacity: 0;
  }
  10% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    transform: translateY(200px);
  }
}

ポイント

白い文字と青い文字を重ねて同時にアニメーションさせています。レイヤー構造は上から順に

  • 白い文字
  • 青い背景
  • 青い文字
  • 白い背景

となっています。その際、青い背景をoverflow: hiddenとすることで白い文字を青い背景の上のみで表示させます。

おわりに

もっと効率的の良い書き方があるかもしれません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0