CSSでmax-widthプロパティをアニメーションさせる方法
CSSでは、max-widthプロパティも他のアニメーション対応プロパティと同様に、@keyframesルールとanimationプロパティを組み合わせることで、滑らかなアニメーションを実現できます。
以下の例では、div要素に対して3秒間のアニメーションを適用し、アニメーションの進行度が30%に達した時点でmax-widthが250pxになるように指定しています。
サンプルコード
<!DOCTYPE html>
<html>
<head>
<style>
div {
overflow: auto;
background-color: blue;
color: white;
border: 1px solid black;
animation: myanim 3s;
}
@keyframes myanim {
30% {
max-width: 250px;
}
}
</style>
</head>
<body>
<h1>Example of max-width</h1>
<div>
<p>This is demo text. This is demo text. This is demo text.
This is demo text. This is demo text. This is demo text.
This is demo text. This is demo text. This is demo text.
This is demo text. This is demo text. This is demo text.
This is demo text. This is demo text. This is demo text.
This is demo text. This is demo text. This is demo text.
This is demo text. This is demo text. This is demo text.
</p>
</div>
</body>
</html>
コードのポイント
- @keyframes myanim: アニメーションの各段階におけるスタイルを定義します。この例では、進行度30%の時点で
max-widthを250pxに設定しています。 - animation: myanim 3s: 定義したキーフレーム「myanim」を3秒かけて実行するよう指定しています。
- overflow: auto: 要素の幅が狭まってコンテンツが収まりきらなくなった場合に、スクロールバーを自動的に表示します。
- background-color / border: アニメーション中の幅の変化を視覚的に分かりやすくするために設定しています。
応用のヒント
30%以外にも0%や100%など複数のキーフレームを追加することで、より複雑な幅の変化を表現できます。また、animationプロパティにinfiniteを加えればアニメーションを繰り返し実行することも可能です。
-
CSSでmin-height(最小の高さ)プロパティをアニメーションさせる方法
CSSで min-height(最小の高さ)プロパティにアニメーションを適用するには、@keyframes ルールと animation プロパティを組み合わせて使用します。以下のサンプルコードでは、div要素に対して3秒間のアニメーションを無限に繰り返すよう設定し、アニメーション進行度が30%の時点で min-height を250pxまで変化させています。コード例<!DOCTYPE html> <html> <head> <style>  
-
CSSでmax-height(最大高さ)をアニメーションさせる方法
CSSでは、max-heightプロパティにも@keyframesを使ったアニメーションを適用できます。要素の高さが徐々に変化するエフェクトを作りたい場合に便利です。以下のコードを実行して、実際の動きを確認してみましょう。 サンプルコード <!DOCTYPE html> <html> <head> <style> div { wi