CSS – YouTubeの動画を縦横比固定で埋め込む
CSSを使い埋め込まれたYouTubeの動画を縦横比固定でレスポンシブ対応させる方法についてご紹介します。
例
例えば下記のようにdiv
で囲まれた状態のYouTube動画がある場合。
<div class="wrap-youtube">
<iframe title="CG5 - Noot Noot (song)" width="500" height="281" src="https://www.youtube.com/embed/9aPGUo5F4Dg?feature=oembed" 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は下記のように設定します。
.wrap-youtube{
height: 0;
margin-bottom: 1rem;
position: relative;
padding-bottom: 56.25%;
padding-top: 0;
}
.wrap-youtube iframe{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}