プログラミング備忘録 foo

YouTube動画掲載

目的

  • YouTube動画をWebページに載せたい。

実行結果(※音が出ます)

解説

コピーした<iframe>〜</iframe>のコードを下記のHTMLのように使います。

HTML

<div class="layout_9_3">
	<iframe width="560" height="315" src="https://www.youtube.com/embed/xRL5uBMHnRQ?si=2w9t6ldiDz9ILzh7" 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>
  • YouTubeからコピーしたこのコードにはwidth="560"と書いてあります。載せるWebページの横幅がW560超でも、引き伸ばされて画質が荒くなる等の問題は基本的にありません。問題が生じた場合のみ修正すればOKです。
  • .mp4を載せる時と違い、特定のシーンを指定して再生前に表示し、実質サムネイル化する手法はYouTube動画では出来ません。

CSS

.layout_9_3 {
	width: 96%;
	margin-top: 0px;
	margin-right: auto;
	margin-bottom: 0px;
	margin-left: auto;
	aspect-ratio: 560/315;
}

.layout_9_3 iframe {
	display: block;
	width: 100%;
	height: 100%;
	border: none;
}
  • aspect-ratioの値は動画サイズをそのまま書けばOKです。上記動画はW560×H315なので7行目でaspect-ratio: 560/315;と書いています。