I want to scale an iFrame through CSS to width: 100%
, and the height should scale proportionally to the width.
With an <img>
tag this works fine.
Both the image and the iFrame have defined width and height in the html.
Here some examples:
<html> <style> #a{ width: 500px; } img{ width: 100%; height: auto } </style> <body> <div id="a"> <img src="http://lorempixel.com/200/150/" width="200" height="150" /> </div> </body>
This works great on images, but I would like the same behaviour for iFrames:
<html> <style> #a{ width: 900px; background: grey;} iframe{ width: 100%; height: auto } </style> <body> <div id="a"> <iframe width="560" height="315" src="http://www.youtube.com/embed/RksyMaJiD8Y" frameborder="0" allowfullscreen></iframe> </div> </body>
The iFrame renders 100% wide but does not scale it's height proportional like the image does.
To size the <iframe> , we ignore the width="560" height="315" element properties, and instead use the CSS properties width:100%;height:100%; . That's it: a full-width <iframe> with fixed aspect ratio. Enjoy.
given the iframe is directly under body. If the iframe has a parent between itself and the body, the iframe will still get the height of its parent. One must explicitly set the height of every parent to 100% as well (if that's what one wants).
What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.
if you specify width:100%, the element's total width will be 100% of its containing block plus any horizontal margin, padding and border. So, next time you find yourself setting the width of a block level element to 100% to make it occupy all available width, consider if what you really want is setting it to auto.
Big difference between an image and an iframe is the fact that an image keeps its aspect-ratio. You could combine an image and an iframe with will result in a responsive iframe. Hope this answerers your question.
Check this link for example : http://jsfiddle.net/Masau/7WRHM/
HTML:
<div class="wrapper"> <div class="h_iframe"> <!-- a transparent image is preferable --> <img class="ratio" src="http://placehold.it/16x9"/> <iframe src="http://www.youtube.com/embed/WsFWhL4Y84Y" frameborder="0" allowfullscreen></iframe> </div> <p>Please scale the "result" window to notice the effect.</p> </div>
CSS:
html,body {height:100%;} .wrapper {width:80%;height:100%;margin:0 auto;background:#CCC} .h_iframe {position:relative;} .h_iframe .ratio {display:block;width:100%;height:auto;} .h_iframe iframe {position:absolute;top:0;left:0;width:100%; height:100%;}
note: This only works with a fixed aspect-ratio.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With