CSSで作るスイングアニメーション効果の実装方法
スイング(Swing)アニメーションは、吊り下げられた要素や軸を中心とした要素を、前後・左右に揺らす動きを表現できるCSSアニメーション効果です。振り子のような自然な揺れを再現でき、ロゴやバナー、アイコンなどに注目を集める演出として活用できます。
スイングアニメーションの仕組み
スイングアニメーションは、主に次のCSS機能を組み合わせて実装します。
transform-origin: top center;… 要素の上部中央を回転の基点に設定し、ぶら下がっているように見せる@keyframesとrotate()… 回転角度を15°→ -10°→ 5°→ -5°→ 0°と段階的に変化させ、振幅が徐々に小さくなる減衰揺れを表現するanimation-duration/animation-fill-mode… 再生時間と、アニメーション終了後のスタイルの保持方法を指定する
コード例
以下は、画像にスイングアニメーションを適用する完全なHTMLのサンプルです。「Reload page」ボタンをクリックするとページが再読み込みされ、アニメーションを最初から確認できます。
<html>
<head>
<style>
.animated {
background-image: url(/css/images/logo.png);
background-repeat: no-repeat;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 10s;
animation-duration: 10s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@-webkit-keyframes swing {
20%, 40%, 60%, 80%, 100% { -webkit-transform-origin: top center; }
20% { -webkit-transform: rotate(15deg); }
40% { -webkit-transform: rotate(-10deg); }
60% { -webkit-transform: rotate(5deg); }
80% { -webkit-transform: rotate(-5deg); }
100% { -webkit-transform: rotate(0deg); }
}
@keyframes swing {
20% { transform: rotate(15deg); }
40% { transform: rotate(-10deg); }
60% { transform: rotate(5deg); }
80% { transform: rotate(-5deg); }
100% { transform: rotate(0deg); }
}
.swing {
-webkit-transform-origin: top center;
transform-origin: top center;
-webkit-animation-name: swing;
animation-name: swing;
}
</style>
</head>
<body>
<div id = "animated-example" class = "animated swing"></div>
<button onclick = "myFunction()">Reload page</button>
<script>
function myFunction() {
location.reload();
}
</script>
</body>
</html>
実装のポイント
- ベンダープレフィックスについて: サンプルでは古いSafariやChrome向けに
-webkit-付きの記述を併記しています。最新のブラウザのみを対象とする場合は、標準の@keyframesやanimation-*プロパティだけで問題なく動作します。 - 回転基点の調整:
transform-originの値を変更すると揺れの印象が変わります。例えばtop leftに設定すると、左上を軸にして揺れるようになります。 - 速度の調整:
animation-durationの値を短くすると素早い揺れに、長くするとゆったりとした揺れになります。 - 繰り返し再生:
animation-iteration-count: infinite;を追加すれば、揺れを永続的に繰り返すアニメーションにもできます。
まとめ
CSSだけで完結するスイングアニメーションは、JavaScript不要で軽量に動作するのが大きな魅力です。transform-origin と @keyframes の組み合わせを覚えておけば、揺れる看板やぶら下がるオブジェクトなど、さまざまなWeb演出へ応用できます。
-
CSSで実装するウォブル(揺れ)アニメーション効果の作り方
CSSの@keyframesとtransformプロパティを組み合わせることで、要素を左右に揺らす「ウォブル(wobble)アニメーション」を簡単に実装できます。移動と回転を段階的に変化させることで、まるで物体がぐらついているような自然な動きを表現できるのが特徴です。 以下のサンプルコードを実行して、実際のアニメーション効果を確認してみましょう。 サンプルコード <html> <head> <style> .animate
-
CSSで実現するTada(タダ)アニメーション効果の作り方
CSSを使えば、要素に「Tada」と呼ばれる揺れるようなアニメーション効果を簡単に追加できます。Tadaアニメーションは、要素が左右に傾きながら拡大・縮小を繰り返すことで、ユーザーの注意を引きつける演出としてよく使われます。ロゴやボタンを目立たせたい場面などに効果的です。以下のコードを実行すると、実際にTadaアニメーションの動作を確認できます。サンプルコード<html> <head> <style> .animated {