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 | <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 | <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 | <div style="position:relative;padding-bottom:68.57%;"> |
References
Preserve iframe Aspect Ratio