LoginSignup
5
10

More than 5 years have passed since last update.

transitionプロパティによるCSSアニメーションの基礎

Posted at

はじめに

cssを使った簡単なアニメーションを作る。
cssでアニメーションを作成する手法としてはanimationプロパティを用いたものとtransitionプロパティを用いたものがある。
今回はtransitionを用いてアニメーションを作る。
transitionはanimationと比較して:hoverなどのトリガーが必要となる。

アニメーション前

アニメーション前のhtmlとcssは以下の通り。
ブラウザから見ると青色の二つのブロックが並ぶ。
これらのブロックの上にカーソルを載せた時とクリックしたときにブロックが横に伸びるアニメーションを作成する。

html
<div class="box hover">:hover</div>
<div class="box click">:click</div>
css
.box {
     width: 200px;
     height: 100px;
     margin: 10px;
     background-color: #33f;
     color: white;
     padding: 10px;
}

transitionプロパティ

transitionは時間変化を指定するプロパティ。
秒数を指定すると変化に掛かる時間を設定する事ができる。
今回は1sを指定した。これにより1秒で対象が変化する。

transitionプロパティを追加
.box {
     width: 200px;
     height: 100px;
     margin: 10px;
     background-color: #33f;
     color: white;
     padding: 10px;
     transition: 1s;
}

ホバー状態

ホバー状態(マウスカーソルが上に乗っている状態)にブロックが横に伸びるように設定する。
擬似クラス:hoverを用いてwidthを設定すれば良い。
今回は400pxを設定した。また、background-colorも変化させている。

hover
.box.hover:hover {
     width: 400px;
     background-color: #f33;
}

クリック時

クリック時に以下のようなクラスを要素に追加することで実装する。

clickedクラス
.box.click.cliced {
     width: 400px;
     background-color: #3f3;
}

jQueryを使うので<head>に以下を追加する必要がある

jQueryのインクルード
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>

jQueryのtoggleClassを用いる。
toggleClassは指定したCSSクラスを対象の要素が持っていなければ追加、持っていれば削除する。

.clickedの追加
$(function() {
    $(".click").click(function() {
         $(this).toggleClass("clicked");
     });
});

デモ

5
10
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
5
10