Youtube動画をレスポンシブで埋め込む方法
Youtube動画をレスポンシブで埋め込む方法をご紹介します。
前準備
まずは埋め込みコードをコピーします。
1 |
<iframe width="560" height="315" src="https://www.youtube.com/embed/動画ID" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> |
サイトの任意の位置にコピーしたコードを貼り付けます。
任意のclass(またはid)を付けたdivで囲みます。
1 2 3 |
<div class="youtube_wrap"> <iframe width="560" height="315" src="https://www.youtube.com/embed/動画ID" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> </div> |
cssでのレスポンシブ対応
方法1: aspect-ratio を使用
aspect-ratio を 16 / 9 に指定することで、YouTube の標準的な縦横比(16:9)を維持できます。
aspect-ratio は IE のほか、Chrome 88 未満や Edge 88 未満では未対応ですが、現在の主要ブラウザでは問題なく使用できます。
1 2 3 4 5 6 7 8 9 |
.youtube_wrap { width: 100%; aspect-ratio: 16 / 9; } .youtube_wrap iframe { width: 100%; height: 100%; } |
方法2: padding-top を使用
1 2 3 4 5 6 7 |
.youtube_wrap { position: relative; width: 100%; height: 0; padding-top: 56.25%; overflow: hidden; } |
縦横比を保ったまま可変する親要素を作ります。
親要素の幅に対して、高さを相対値で指定します。
Youtubeの標準縦横比16:9 の比率を維持するため、
高さ(9)を幅(16)で割り、100% を掛けることで padding-top: 56.25% を指定します。
この値により、親要素の幅に対して適切な高さが自動で決まります。
1 2 3 4 5 6 7 |
.youtube_wrap iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } |
枠ぴったりに動画が収まるよう、position: absolute; を指定します。
iframe タグの width や height 属性は HTML で設定されていますが、CSS によって width: 100%; height: 100%; を指定することで、親要素にフィットするように上書きされます。