自作CSSアニメーションで得た学び
CSSを学習中の方向けに書いてみましたので読んでくれたら嬉しいです。
前提となってる記事はこれです。
↑ 頑張ってイケメンなアニメーション作ったっちゃん。せっかくやけん見てってくれてもいいとよ。
CSSで役立つテクニック
①要素の位置指定は「absolute&transform」が使いやすい。
「position:absolute」で他要素に干渉されない状態にし、「transform: translate(Xpx,Ypx)」で位置を指定するという理屈。
↓文字じゃよく分からんのでコードで
<div class="container">
<div class="background"></div>
<div class="background2"></div>
<div class="laser"></div>
<div class="laser2"></div>
</div>
.container {
position: relative;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.background {
position: absolute;
rotate: 0deg; /* レーザーの角度を指定 */
animation-name: firstBackgroundEffect;
animation-duration: 0.4s;
animation-fill-mode: forwards;
}
.background2 {
position: absolute;
rotate: 0deg; /* レーザーの角度を指定 */
animation-name: secondBackgroundEffect;
animation-delay: 0.5s;
animation-duration: 0.2s;
animation-fill-mode: forwards;
}
.laser {
width: 1px;
height: 1px;
rotate: 0deg; /* レーザーの角度を指定 */
animation-name: firstLaserEffect;
animation-duration: 0.8s;
animation-fill-mode: forwards;
}
.laser2 {
position: absolute;
width: 1px;
height: 1px;
rotate: 0deg; /* レーザーの角度を指定 */
animation-name: secondLaserEffect;
animation-duration: 0.4s;
animation-delay: 0.5s;
animation-fill-mode: forwards;
}
containerの子要素は縦横中央寄せになっています。
その子要素にposition:absoluteを付けることで、他子要素に干渉をされない状態にします。
その状態でtransformで位置を変えることで他要素に関係なく場所を指定できるワケですね。
②両端がとがった直線はradial-gradientで描ける
<span class="thin-border"></span>
.thin-border {
height: 4px;
width: 400px;
background-color: white;
background: radial-gradient( white 30%, transparent 60%);
}
これをアニメーションで動かせば超クールなスペシャルレーザー直線作れまふ。カッコいいから見てください。
③「animation & @keyframe」しか勝たん
アニメーションを作るには「transition」も使えますが「animation & @keyframe」を使っておけば大体のアニメーションは書けます。
「transition」か「animation & @keyframe」どっち使おうか迷うぐらいだったらとりあえず「animation & @keyframe」使うといいかもしれません。
おまけ
アニメーションの開始遅延は「animation-delay」ではなくJavaScriptの「setTimeout()でクラスの付与を遅らせる」というやり方が楽でした。
おすすめポイント
元あるCSSに手を加えずにアニメーションを遅らせることができる点です。
CSSにアニメーション色々書いてたらanimation-delayを書く場所を探すの面倒だったり、CSSをいじったことによる思わぬ挙動をを回避できるのがメリットかなーと思ったり思わなかったり。
デメリットあるかもしれんけん、よーと考えて使いーね。
おわりに
両端が尖った直線はクールなサイトに使える。