1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

縦向きのYoutube動画をいい感じに埋め込むには?

Posted at

はじめに

イメージはこんなんです!

Youtubeの埋め込み方でいい感じにレスポンシブ対応させる記事を見てると、大体が横向き動画のパターンだったので、、、:sweat_smile:

「あれ?縦向きの動画はどうするんや??」
と思ったので、調べた結果をまとめます!

パターン1aspect-ratio を使った方法

aspect-ratioはIEやアップデートされていないSafariなどでは使用できないらしいので、要注意です!
横向き動画はaspect-ratio: 16 / 9;なので、単純に9 / 16と逆にすればOKですw
これだけで縦向き動画がレスポンシブで埋め込めます!便利〜〜

   <div class="video">
        <iframe
          width="100%"
          height="100%"
          src="https://www.youtube.com/embed/bWEN90ssyMU"
          title="YouTube video player"
          frameborder="0"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowfullscreen
        ></iframe>
      </div>
.video {
  width: 100%;
  aspect-ratio: 9 / 16;
}

.video iframe {
  width: 100%;
  height: 100%;
}

パターン2padding-top を使った方法

※HTMLに変化はありません

なぜ padding-top が 56.25% なのか?
padding-top の%指定は、要素の横幅に対する割合で計算されます。
例を挙げると、横幅 100px の要素に対して、padding-top を 50% に指定した場合、100px の 50% 分なので、padding-top は 50px になります。
今回の埋め込み動画の場合は、縦横比が 16:9 となっていることが多いです。
56.25% という数値は、9 / 16 = 56.25 から算出されています。横幅 16 に対して縦幅が 9 になるように計算されるので、要素の width が可変した分、縦幅もぴったり 16:9 の割合で可変してくれます。

9 / 16 = 56.25なので、この計算式を逆にして16 / 9 = 1.7777~なので**padding-topは170%**になります!

.video {
  position: relative;
  height: 0;
  // padding: 30px 0 56.25%; これが横向き!
  padding: 30px 0 170%;
  overflow: hidden;
}

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

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?