YouTube動画をWebサイトに埋め込む際に、レスポンシブ対応(=アスペクト比を維持したまま拡大・縮小)する方法
CSS

YouTube動画をWebサイトに埋め込む際に、レスポンシブ対応(=アスペクト比を維持したまま拡大・縮小)する方法

YouTube動画の埋め込み自体は本サイトからiframeのコードをコピペすれば簡単に実現できるのですが、レスポンシブ対応する際はCSSで調整してあげる必要があります。

方法

HTML

コピペしてきたiframeをdivで囲んであげます

<div class="video-wrap">
     <iframe width="560" height="315" src="https://www.youtube.com/embed/aqa9h-nL-TA" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>


CSS

.video-wrap {
  position: relative;
  width: 100%;
  height: 0;
  padding-top: 56.25%; // ここがポイント。動画の縦横の比率が16:9であれば 6 / 19 * 100 = 56.25を設定
}


.video-wrap > iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}


最近はあまり見かけないですが、動画の比率が4:3の場合は 3 / 4 * 100 = 75%を.video-wrapのpadding-topに指定すれば良いです。

動画の幅を変えたい場合

全幅で表示するのではなく、幅50%や33.333%にして動画を並べたいこともあるかと思います。その場合は.video-wrapをさらにdivで囲み、そのdivに好きな幅を指定すればOK。

HTML

幅50%で動画を2つ横に並べる

<div class="video-row">
    <div class="video-col">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/aqa9h-nL-TA" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
     </div>
    <div class="video-col">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/aqa9h-nL-TA" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
     </div>
</div>


CSS

display:flexで横に並べる

// 追加したコード
.video-row {
  width: 100%;
  display: flex;
  justify-content: center;
 align-items: center;
 margin: 0 -48px;
}

.video-col {
 width: 50%;
 padding: 0 24px;
}
// end

.video-wrap {
  position: relative;
  width: 100%;
  height: 0;
  padding-top: 56.25%; // ここがポイント。動画の縦横の比率が16:9であれば 6 / 19 * 100 = 56.25を設定
}


.video-wrap > iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}



よく使う手法なのですが毎回忘れてコードを探しに行きます

~~ END ~~