Hanfei Sun
Hanfei Sun

Reputation: 47051

How to make Youtube embeded video responsive

The example website: http://zh.gopro.com/

As can be seen, the header youtube video is responsive (resize automatically when window resizes), the <iframe> codes are below:

<iframe id="bluetube-player-1" frameborder="0" allowfullscreen="1" title="YouTube video player" width="944" height="531" src="https://www.youtube.com/embed/F1jpCBPiWS4?showinfo=0&amp;rel=0&amp;controls=0&amp;modestbranding=0&amp;wmode=transparent&amp;enablejsapi=1&amp;origin=http%3A%2F%2Fzh.gopro.com" style="width: 1125px; height: 633px; left: 0px; top: -158.5px; position: relative;">

</iframe>

I found the width, height and style attributes are all be responsive in this page. But I didn't find how the author makes this (css or js?).. I tried to find jQuery method by using bluetube to search but still didn't understand how it works..

Does anyone have ideas about this?

Upvotes: 0

Views: 1845

Answers (1)

Praxis Ashelin
Praxis Ashelin

Reputation: 5217

The video on your example website is actually not responsive, it doesn't resize properly according to your window (the sides simply get clipped). He is most likely just using a media query to resize the video once the window is smaller than a certain width (most likely aimed for mobile).

However, what you want to achieve is actually possible, if you use a container element which has an intrinsic aspect ratio, then absolute position the video within that.

HTML

<div class="videoWrapper">
    <!-- Copy & Pasted from YouTube -->
    <!-- The width and height here are ignored, and can actually be removed -->
    <iframe width="560" height="315" src="https://www.youtube.com/embed/ygVQ8R-ZtZA" frameborder="0" allowfullscreen></iframe>
</div>

CSS

.videoWrapper {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 ratio */
    padding-top: 25px;
    height: 0;
}
.videoWrapper iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

JSFiddle demo

Source and more information about responsive video embedding can be found here.

Upvotes: 4

Related Questions