CSS3によるアニメーション効果(transitions)速習

CSS3によるアニメーションは、「-webkit-transition」を使う。

サンプル

.animationLayer {
	width:200px;
	height:50px;
	padding:20px;
	margin:2em auto;
	text-align:center;
	background:#ff0;
	-webkit-transition: 0.5s ease-in-out;
}
.animationLayer:hover {
	width:300px;
	height:100px;
	background:#ccc;
}
.animationInput {
	width:100px;
	-webkit-transition: 0.2s ease-in-out;
}
.animationInput:focus {
	width:200px;
}

上記CSSを反映させたサンプルは下記。(投稿時点でChromeかSafariのみ動作)

hoverでアニメーション

解説

アニメーションを起こす前の標準状態の要素へ「-webkit-transition」を加える。それだけ。

-webkit-transition: 0.5s ease-in-out;

こいつはアニメーションをイン/アウト時に0.5秒で行うという定義。

セットで、hover、active、focusセレクタのスタイルを記述する。
元要素に記述されている width,height や background といった、数値範囲のあるものが主にアニメーションの対象となる。

よく見かける「透明→出現」のアニメーションには opacity を利用する。
※「display」「visibility」ではON/OFFでしかなく、アニメーションしない。

応用

.sample_button {
	width:100px;
	height:100px;
	border-radius:100px;
	margin:20px auto;
	padding:5px;
	background: -moz-linear-gradient(top, #aaa,#444);
	background: -webkit-gradient(linear, left top, left bottom, from(#aaa),to(#444));
	-webkit-transition: 0.2s ease-in-out;
}
.sample_button:hover {
	padding:10px;
	box-shadow:0 0 10px rgba(255,255,0,1);
}
.sample_button a {
	display:block;
	width:100px;
	height:100px;
	line-height:100px;
	margin:0 auto;
	font-size:14pt;
	text-align:center;
	text-decoration:none;
	color:#000;
	border-radius:100px;
	text-shadow:0px 1px 0 rgba(255,255,255,1);
	box-shadow:0px 0px 2px rgba(0,0,0,1);
	background: -moz-linear-gradient(top, #eee,#999);
	background: -webkit-gradient(linear, left top, left bottom, from(#eee),to(#999));
	-webkit-transition: 0.2s ease-in-out;
}
.sample_button:hover a {
	color:#660;
}
.sample_button a:active {
	background: -moz-linear-gradient(top, #999,#eee);
	background: -webkit-gradient(linear, left top, left bottom, from(#999),to(#eee));
}

※グラデーション使ってるのでIEだとアニメーションどころか表示自体ほぼされません。

筆者について

KaBuKi
ゲームとジョジョを愛するファミッ子世代。好きな言葉は「機能美」。
公私ともにWebサービスを作る系男子。