YouTubeの動画をWebページに埋め込む際に、レスポンシブ対応にするためのCSSを適用すると、画面サイズに応じて動画が自動的に縮小・拡大され、モバイルデバイスやタブレットでも快適に閲覧できるようになります。以下の手順で、YouTube動画をレスポンシブ対応にする方法を紹介します。
手順
- HTMLでYouTubeのiframeを埋め込む
- CSSでレスポンシブ対応させる
1. HTMLでYouTubeのiframeを埋め込む
まず、YouTube動画を埋め込むために、YouTubeの「共有」オプションから「埋め込みコード」を取得し、それをHTMLに貼り付けます。例えば、以下のようにiframeタグを使います。
<div class="video-container">
<iframe width="560" height="315" src="https://www.youtube.com/embed/動画ID" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
2. CSSでレスポンシブ対応させる
次に、CSSを使って、iframeをレスポンシブに対応させます。以下のCSSを追加することで、画面サイズに応じてYouTube動画のサイズが調整されるようになります。
.video-container {
position: relative;
width: 100%;
padding-bottom: 56.25%; /* 16:9 アスペクト比を維持するための値 (高さを幅の56.25%に設定) */
height: 0;
overflow: hidden;
}
.video-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
CSSの説明
.video-container: 動画を埋め込むコンテナ要素です。padding-bottom: 56.25%は16:9のアスペクト比を維持するための値です。padding-bottomの値はアスペクト比によって調整できます。例えば、4:3の比率の場合はpadding-bottom: 75%に変更します。iframe: 動画を実際に表示する部分です。width: 100%とheight: 100%で、親要素(.video-container)のサイズに合わせて、iframeが自動的にリサイズされるようにしています。
完成したHTML + CSS
<!DOCTYPE html> <html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>レスポンシブYouTube埋め込み</title>
<style>
.video-container {
position: relative;
width: 100%;
padding-bottom: 56.25%; /* 16:9 アスペクト比 */
height: 0; overflow: hidden;
}
.video-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="video-container">
<iframe src="https://www.youtube.com/embed/動画ID" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</body>
</html>
この方法で、YouTube動画はどのデバイスでも正しいアスペクト比を維持しつつ、レスポンシブ対応されます。
以下のような感じです。