iframeをレスポンシブWebデザインに対応する方法
HTML のインラインフレーム要素であるiframeをレスポンシブWebデザインに対応する方法をご紹介します。
ポイント
ポイントは以下の通りです。
- htmlのiframeをdiv(親)で囲む
- cssで、親のpositionにrelative、iframeにabsoluteを指定
- cssで、親のheightに0を指定
- cssで、親のpadding-top(bottomでもOK)に画面比率を指定
画面比率
画面比率は以下の計算式で求められます。
画面比率(%) = 高さ÷幅×100
例1)4:3の場合
3÷4×100 = 75%
例2)16:9の場合
9÷16×100 = 56.25%
実装例
html
<div class="iframe-parent"> <iframe width="640" height="360" src="https://www.youtube.com/embed/PmrWwYTlAVQ" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div>
css
.iframe-parent {
position: relative;
height: 0;
overflow: hidden;
padding-top: 56.25%;
}
.iframe-parent iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
以上の記述により、iframe要素(ここではYouTubeの動画画面)が画面サイズに応じてレスポンシブに拡大または縮小されて表示されます。
参考
[YouTube] iframeのレスポンシブ対応
https://qiita.com/0084ken/items/e7d35d2a8eb507f4d59c
Design Spice
https://design-spice.com/2014/03/24/percentag/
![]()


