Preserve iframe Aspect Ratio

Introduction

iframe is very commonly used in HTML nowadays. In certain scenarios, such as game and video play, we would like to fix the aspect ratio while the iframe is responsive to different window dimensions.

Example

Dyna Blaster (Bomberman) was a popular DOS game that is now archived in Internet Archive. Internet Archive allows the users to embed the game on their own website using iframe. The following the the iframe code generated by the Internet Archive for the game.

1
2
3
4
5
6
7
8
9
10
<iframe
src="https://archive.org/embed/chenall_dyna"
width="560"
height="384"
frameborder="0"
webkitallowfullscreen="true"
mozallowfullscreen="true"
allowfullscreen
>
</iframe>


The problem of this iframe code is that the iframe is fixed size (560px in width and 384px in height) and is not responsive to different window dimensions.

We could use relative size for the iframe, i.e., 100% in width and 100% in height, so that it’s responsive to different window dimensions. However, this time, the aspect ratio is completely lost.

1
2
3
4
5
6
7
8
9
10
<iframe
src="https://archive.org/embed/chenall_dyna"
width="100%"
height="100%"
frameborder="0"
webkitallowfullscreen="true"
mozallowfullscreen="true"
allowfullscreen
>
</iframe>


If we wrap the iframe with a div and use position and padding-bottom attributes, we could make the iframe both responsive to different window dimensions and maintain aspect ratio. Notice that in our case, the padding-bottom:68.57% value is calculated using the native aspect ratio. That is to say, 68.57% = 384 / 560.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div style="position:relative;padding-bottom:68.57%;">
<iframe
style="width:100%;height:100%;position:absolute;left:0px;top:0px;"
frameborder="0"
width="100%"
height="100%"
webkitallowfullscreen="true"
mozallowfullscreen="true"
allowfullscreen
src="https://archive.org/embed/chenall_dyna"
>
</iframe>
</div>
<br />

References

Author

Lei Mao

Posted on

03-11-2024

Updated on

03-11-2024

Licensed under


Comments