We all embed iframe in our website. Embedding works well when we specify height and width of images in pixels. While building a responsive website we specify iframe width in percentage then their height depends on the aspect ratio. The height no way changes according to the change in width of the iframe. In this post I will provide a trick using which we can make all iframes respect their aspect ratio when width changes due to viewport resize.
CSS padding-top property
padding-top
in percentage depends on the width of the containing block.
For example parent block has width
of 100px. We created a block inside it and specified its padding-top to be 50%. Then the inside block will have padding-top
as 50px.
Using this trick we can create a responsive aspect ratio maintaining block. And then just absolute position our iframe in the block with full width and height. Here is example code
In the above example our containing block is of 4:3 aspect ratio therefore the iFrame is also of 4:3 aspect ratio.
Conclusion
This technique can be useful while embedding youtube videos, vimeo videos etc in an responsive website.
Leave a Reply