This past winter, I was introduced to a concept which was actually developed back in 2009. Namely, if you have video content on your website, and you want a responsive design, there’s a very clever trick which requires a wrapper
div and a bit of CSS.
Just now, I was able to set this up for my own site, with an extra twist: for each
iframe embed I have on my page, I can loop through and replace it with a wrapped version. I can also then find the original aspect ratios, if available, and make sure that persists, regardless of the width of the page / elements. That’s enough words, so here’s the code:
The new thing here is that we can set the
paddingBottom dynamically, via JS, with a fallback if needed, and the other CSS rules take care of the rest. If we wanted to depend on jQuery, this code could be even smaller, yet even as it is, we have a pretty compact solution.
Since I’m running WordPress here, I also was able to integrate this easily with the JetPack Infinite Scroll plugin, by adding a callback on
post-load. This means that after any new posts have been added, I wrap any new content in there as well.
I should also point out that it would be more efficient to have these wrappers in the HTML itself, rather than asking JS to make replacements on its own. The main reason I’m not doing that here is because WordPress graciously supports oEmbed,which means the HTML embed code is generated dynamically.
This way there’s a lot less for me to maintain. I can plop in the URL in my post, and forget about the rest. I can also clear out the cached versions, and on the next page view it’ll get that embed code again.
I’m pretty happy where this is at, and I’d like you to try it out. Fork what’s there and add or integrate whatever you’d like. If you have any questions, you can write me, post on the GitHub Gist, or comment here. Thanks!