Skip to content

Instantly share code, notes, and snippets.

@manueldev
Created March 26, 2020 22:46
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 manueldev/736c451ee7463c13ee9b988d1cd98f38 to your computer and use it in GitHub Desktop.
Save manueldev/736c451ee7463c13ee9b988d1cd98f38 to your computer and use it in GitHub Desktop.
Responsive iframe solution.
When embedding iframes for content such as videos, most services like YouTube and Vimeo will provide you a snippet of code like the one below:
<iframe width="560" height="315" src="//www.youtube.com/embed/KMYrIi_Mt8A" allowfullscreen></iframe>
Notice I removed the frameborder attribute. If you’re using HTML5, that attribute is no longer supported.
First of all, remove the width and height attributes. Keeping those attributes forces the content to stay at that size regardless of the screen size. This causes problems in responsive layouts when the screen size is smaller than the width of the iframe. Though we could use CSS to force the size, why have them if their not being used — less code is beautiful code.
<iframe src="//www.youtube.com/embed/KMYrIi_Mt8A" allowfullscreen></iframe>
Next, let’s add a container with a class around the iframe:
<div class="iframe-container">
<iframe src="//www.youtube.com/embed/KMYrIi_Mt8A" allowfullscreen></iframe>
</div>
Now, we add a little touch of CSS magic to make the iframe responsive. The same way we did in the “Resize Videos Proportionally with Intrinsic Ratios“.
.iframe-container {
overflow: hidden;
padding-top: 56.25%;
position: relative;
}
.iframe-container iframe {
border: 0;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}
/* 4x3 Aspect Ratio */
.iframe-container-4x3 {
padding-top: 75%;
}
IMPORTANT: Don’t forget to apply an aspect ratio
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment