YouTubeのレスポンシブ対応サンプル

<div id="ytplayerWrap">
  <div id="ytplayer"></div>
</div>

@media screen and (max-width: 640px) {
  #ytplayerWrap {
    position: relative;
    width: 100%;
    padding-top: 56.25%;
  }

  #ytplayer {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}
const script = document.createElement('script')
script.src = 'https://www.youtube.com/player_api'
document.head.appendChild(script)

function onYouTubePlayerAPIReady() {
  new YT.Player('ytplayer', {
    videoId: 'M7lc1UVf-VE',
  })
}

元記事を表示する