Making YouTube, Vimeo and Instagram IFRAMES responsive in Squarespace
More in Plugins, Scripting and Styling
This Squarespace tip is a jQuery script that makes embedded YouTube, Vimeo and Instagram videos display correctly in responsive layouts.
See also - Adding autoplay video banners to a Squarespace website.
Why is the responsive Iframe script needed?
The EMBED codes for YouTube, Vimeo and Instagram all use Iframes that have fixed heights and widths.
The problem with this is that embedded content does not resize on smaller screen sizes and can break layouts.
Using a DIV wrapper to allow responsive IFRAME styling
There is a fix, described on the Avex designs website, that involves wrapping a DIV around the IFRAME that then allows the fixed pixel sizing to be overriden by percentage sizing, and also ensures that the embedded content's aspect ratio is preserved.
However, this fix requires content authors to remember to manually wrap a DIV around the Iframe code. Rather than add complexity to the authors work, I decided to write a simple jQuery script that looks for IFRAMES on a page, checks whether they are referencing YouTube, Vimeo, or Instagram and wraps with a DIV that allows CSS styling for each source type.
The jQuery code
You should have a reference to JQuery in your site header and then position the following code after the jQuery reference.
<script type="text/javascript">
/* Script to find all IFRAMES on a page and, if they are of a certain media type, wrap them in a DIV so that they can be styled to be responsive */
$(document).ready(function () {
$('iframe[src*="youtube.com"]').wrap('<div class="youtubeWrapper" />');
$('iframe[src*="vimeo.com"]').wrap('<div class="vimeoWrapper" />');
$('iframe[src*="instagram.com"]').wrap('<div class="instagramWrapper" />');
});
</script>
The CSS
The following CSS should be added to your site's CSS file
<style>
/* Responsive IFRAME Embed Encoding
Adapts fixed pixel IFRAME sizes and makes them responsive. */
/* First, define the common wrapper elements
Padding-top is for the fixed height header of the embedded content */
.youtubeWrapper, .vimeoWrapper, .instagramWrapper {
position: relative;
padding-top: 30px; height: 0; overflow: hidden;
}
/* Set the padding-bottom for 16:9 aspect ratio video from YouTube & Vimeo */
.youtubeWrapper, .vimeoWrapper {
padding-bottom: 56.25%;
}
/* Set padding-bottom for 5:6 aspect ratio Instagram content */
.instagramWrapper {
padding-bottom: 120%;
}
/* For each content source, set the IFRAME to be top left and occupy 100% of width and height of the containing DIV wrapper */
.youtubeWrapper iframe,
.youtubeWrapper object,
.youtubeWrapper embed,
.vimeoWrapper iframe,
.vimeoWrapper object,
.vimeoWrapper embed,
.instagramWrapper iframe,
.instagramWrapper object,
.instagramWrapper embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>