animation-play-state(再生・一時停止)のCSS動作テストツール
CSSのanimation-play-stateプロパティ(再生・一時停止)の挙動をテストするツールです。合わせてanimation-directionでの逆再生もテストしています。
プレビュー
<div class="test-container">
<div class="animation-box"></div>
<div class="controls">
<!-- 再生 -->
<input type="radio" name="state" id="anim-play">
<label for="anim-play" class="btn">再生</label>
<!-- 逆再生 -->
<input type="radio" name="state" id="anim-reverse">
<label for="anim-reverse" class="btn">逆再生</label>
<!-- 一時停止 -->
<input type="radio" name="state" id="anim-pause">
<label for="anim-pause" class="btn">一時停止</label>
</div>
</div>
/* コンテナ */
.test-container {
padding: 20px;
text-align: center;
}
/* アニメーションする要素 */
.test-container .animation-box {
display: inline-block;
width: 100px;
height: 100px;
margin-bottom: 30px;
background: #0091EA;
border-radius: 10px;
/* 初期状態は一時停止にしておく */
animation: rotateAnim 2s linear infinite paused;
}
/* アニメーション定義 */
@keyframes rotateAnim {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* --- ボタンレイアウト --- */
.test-container .controls {
display: flex;
justify-content: center;
gap: 10px;
}
/* ラジオボタンは非表示 */
.test-container input[type="radio"] {
display: none;
}
/* ボタンの見た目 */
.test-container .btn {
padding: 8px 16px;
border: 2px solid #0091EA;
border-radius: 20px;
cursor: pointer;
transition: 0.3s;
font-size: 14px;
user-select: none;
background: #fff;
color: #0091EA;
}
/* 選択中のボタンスタイル */
.test-container input:checked + .btn {
background: #0091EA;
color: white;
}
/* --- 状態制御 --- */
/* 再生: running */
.test-container:has(#anim-play:checked) .animation-box {
animation-play-state: running;
}
/* 一時停止: paused */
.test-container:has(#anim-pause:checked) .animation-box {
animation-play-state: paused;
}
/* 逆再生: reverse + running */
.test-container:has(#anim-reverse:checked) .animation-box {
animation-direction: reverse;
animation-play-state: running;
}
機能・使い方
- CSSの
animation-play-stateプロパティによるアニメーションの再生制御デモです。 animation-play-state: runningで再生、pausedで一時停止します。- 逆再生を行う場合は
animation-direction: reverseを併用します。 - このデモではCSSの
:has()疑似クラスを使用して、ラジオボタンの状態に応じてアニメーションスタイルを切り替えています。
:has()の指定方法、コードの読み方について
このCSSでは、:has() を使うことで、JavaScriptを使わずにラジオボタンのON/OFFに合わせてアニメーションを操作しています。
一見複雑に見えるコードですが、3つの部分に区切って読むと仕組みがよく分かります。
/* 例:再生ボタン(#anim-play)が選ばれている時の指定 */
.test-container:has(#anim-play:checked) .animation-box {
animation-play-state: running;
}
コードの読み解き方(3ステップ)
この指定は、「条件を満たす親要素を探し、その中にある別の要素を操作する」 という書き方になっています。
- 1. どこを見る?(親要素)
-
.test-container:has(...)
まず、外側の枠である.test-containerに注目します。
:has(...)は「(...)を持っているか?」という条件チェックです。 - 2. どんな条件?(中身のチェック)
-
#anim-play:checked
これが条件です。「IDがanim-playの要素(再生ボタン)」に「チェックが入っている(:checked)」かどうかを見ています。
つまり、「再生ボタンが押されている状態のコンテナ」 を探しています。 - 3. 何を変える?(操作対象)
-
.animation-box
条件を満たしたコンテナの中にある.animation-box(回転する箱)に対して、animation-play-state: running(再生)というスタイルを適用します。
まとめると、「親(コンテナ)が、子(ボタン)の状態を見張っていて、ボタンが押されたら、別の兄弟(箱)に命令を出す」 という連携プレイをCSSだけで実現しています。