Last active
June 9, 2018 02:31
-
-
Save letrastudio/fb04b6b91ecb98cfeb825129a8d148f6 to your computer and use it in GitHub Desktop.
Make all iframes in a page responsive, keeping aspect ratio from width/height attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function responsifyEmbeds() { | |
var iframes = document.getElementsByTagName("iframe"); | |
for (var i = 0; i < iframes.length; i++) { | |
var iframe = iframes[i]; | |
var parent = iframe.parentNode; | |
var wrapper, width, height; | |
// ignore iframes with "100%" width (those are presumed to be responsive enough already) | |
if (iframe.getAttribute("width") !== "100%") { | |
// if it isn't already the case, wrap iframe in .embed-container div | |
if (parent.classList.contains("embed-container") === true) { | |
wrapper = parent; | |
} else { | |
wrapper = document.createElement("div"); | |
wrapper.className = "embed-container"; | |
parent.replaceChild(wrapper, iframe); | |
wrapper.appendChild(iframe); | |
} | |
// parse width and height attributes as integers, unless they're percentages | |
if (iframe.hasAttribute("width")) { | |
width = iframe.getAttribute("width").indexOf("%") !== -1 ? false : parseInt(iframe.getAttribute("width")); | |
} | |
if (iframe.hasAttribute("height")) { | |
height = iframe.getAttribute("height").indexOf("%") !== -1 ? false : parseInt(iframe.getAttribute("height")); | |
} | |
// if width and height attributes are both integers, define a custom aspect ratio | |
if (width && height) { | |
var ratio = height / width; | |
wrapper.style.paddingTop = (ratio * 100) + "%"; | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.embed-container { | |
position: relative; | |
padding-top: 56.25%; /* Default to 16:9 ratio */ | |
} | |
.embed-container > iframe { | |
position: absolute; | |
top: 0; | |
left: 0; | |
width: 100%; | |
height: 100%; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment