Skip to content

Instantly share code, notes, and snippets.

@schlessera
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schlessera/9aef9ba9aeb69ca0070e to your computer and use it in GitHub Desktop.
Save schlessera/9aef9ba9aeb69ca0070e to your computer and use it in GitHub Desktop.
Make an IFrame (like video, flash, ...) responsive.
/* Responsive IFrame example
* @author Alain Schlesser <alain.schlesser@gmail.com>
/* The wrapper gets resized using padding-bottom with a percentage value. This
* way, it's height is always directly dependent on its width */
.iframe-wrapper {
/* Necessary so we can position the contained IFrame absolutely */
position: relative;
/* We set height to 0 because we control it indirectly through padding-bottom,
* as the height attribute can't be set with a percentage */
height: 0;
/* Prevent scrollbars */
overflow: hidden;
/* Now comes the important part. The padding-bottom resizes based on the width
* and decides what aspect ratio the container should have.
* 56,25% means we have an aspect ratio of 16:9
* 75% would be an aspect ratio of 4:3
* To get any aspect ratio as a percentage: [height] / [width] * 100 */
padding-bottom: 75%;
}
/* The IFrame inside the wrapper will always be sized to 100% width & height of
* the wrapper */
.iframe-wrapper iframe {
/* ...so we can position it in the top-left corner, overriding the wrapper's
* padding-bottom */
position: absolute;
/* Top-left corner */
top: 0;
left: 0;
/* Completely fill the containing wrapper */
width: 100% !important;
height: 100% !important;
}
<!-- Responsive IFrame example -->
<!-- @author Alain Schlesser <alain.schlesser@gmail.com> -->
<!-- We need a <div> that will wrap the IFrame and resize with the browser. -->
<!-- The IFrame inside will be sized to 100% of this wrapper -->
<div class="iframe-wrapper">
<!-- We provide the IFrame with a width & height that already represents -->
<!-- the correct aspect ratio, so it can set itself up appropriately. -->
<!-- In the example below, we have an aspect ratio of 16:9. -->
<iframe src="https://www.domain.com/iframe-embed/" width="720" height="405"
frameborder="0" style="border:0"></iframe>
</div> <!-- .iframe-wrapper -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment