[CSS] アスペクト比を固定できるaspect-ratioプロパティの使い方
CSSのaspect-ratioプロパティを使うと、レスポンシブデザインをより簡単に実現できます。
本記事では、aspect-ratioを使った画像や背景画像のトリミング方法についてご紹介します。
aspect-ratioプロパティとは
aspect-ratioは、要素の幅と高さの比率を指定するプロパティです。
これにより、指定した比率を保ったまま、要素がリサイズされるようになります。
アスペクト比とは?
アスペクト比とは、要素の幅と高さの比率のことです。
例えば、16:9の比率は、幅が16、縦が9の比率を指します。
【代表的なアスペクト比】
アスペクト比 | 説明 |
---|---|
4:3 | アナログ放送時代のテレビ |
3:2 | 一眼レフカメラ |
16:9 | デジタル放送テレビやYouTube等の動画 |
1:1 | 正方形。インスタグラムやバナー広告など |
1.414:1 | 白銀比。縦横比が変わらない印刷物の用紙規格 |
1.618:1 | 黄金比。最も美しいとされる比率 |
aspect-ratioの使い方
aspect-ratioは、幅と高さの比率をスラッシュ(/)で区切って指定します。
1 2 3 |
.thumb { aspect-ratio: 16 / 9; } |
img画像をトリミングする
・html
1 2 3 |
<div class="img-wrap"> <img src="img01.jpg" alt="" /> </div> |
・css
1 2 3 4 5 |
.img-wrap img { width: 100%; aspect-ratio: 16 / 11; object-fit: cover; } |
aspect-ratioとobject-fit: coverを組み合わせることで、任意のアスペクト比で画像をトリミングできます。
背景画像をトリミングする
・html
1 2 3 |
<div class="img-wrap"> <div class="bg-img-wrap"></div> </div> |
・css
1 2 3 4 5 6 7 8 |
.bg-img-wrap { width: 100%; background-image: url('img01.jpg'); background-repeat: no-repeat; background-position: center; background-size: cover; aspect-ratio: 16 / 11; } |
デモ
See the Pen
[css] aspect-ratio by mkl may (@mkl-may)
on CodePen.
従来の padding-top を使ってアスペクト比を保持する方法
これまで、任意のアスペクト比で画像をトリミングする際は、次のように計算したアスペクト比をpadding-topで保持する方法が主流でした。
・html
1 |
<div class="img-wrap-padding"><img src="images/img01.jpg"></div> |
css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
.img-wrap-padding { width: 300px; overflow: hidden; position: relative; } .img-wrap-padding::before { content: ""; display: block; padding-top: 56.25%; } .img-wrap-padding img { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100%; height: auto; } |
aspect-ratioの登場で、より直感的に、簡潔に、コーディングしやすくなりました。