動画や画像をページいっぱいに表示しつつ、レスポンシブ対応できるobject-fitについて今回は紹介する。
上記のオリジナルの事例は動画だが、今回は画像を使用する。htmlで表示したい画像とテキストを以下のように記述する。
<section class="img-container"> <img alt="test" src="https://sns-gazo.co/twitterheader/wp-content/uploads/2014/04/twitter-new-header_02006-600x200.jpg" /> <div class="callout"> <h1>Object-fit👍</h1> </div> </section>
基本的にはimg
内でobject-fit:cover
とすれば表示されるディスプレイサイズに合わせて目いっぱい画像を表示する。
残りは画像表示のサイズなどを指定している。
文字を画像上に表示するには.callout
内のdisplay
などを指定する。
.img-container { height: 100vh; position: relative; overflow: hidden; } img { object-fit: cover; position: absolute; height:100%; width: 100%; top: 0; left: 0; } h1 { font-weight: 900; color:white; margin: 0 0 1rem; padding: 0; line-height: 1; font-family: Futura, Helvetica, sans-serif; font-size: 5vw; } .callout { position: relative; display: flex; justify-content: center; flex-direction: column; height: 100%; text-align: center; }
以下Code Penで実行すると、どのサイズ(1x,0.5x,0.25x)でも同じように表示されていることが確認できる。
See the Pen object-fit by ATATAT (@atatat) on CodePen.