How to make Youtube embed responsive on the site, when opening want Width appear 100%

Asked

Viewed 3,300 times

5

I already have several embed on my site but do not want to go there and change 1 by 1. what I want is a code to change all Iframes, with 100% width and height adjust responsively.

.conteudo{
  background-color:#f1f1f1;
  width:700px;
  height:700px;
  padding:10px;
}
<body>
  <div class="conteudo">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/-ljBNAt2gwc" frameborder="0" allowfullscreen></iframe>
  </div>
</body>

  • I did that and it worked, just with . css https://www.youtube.com/watch?v=X4t0JxiBeO0

4 answers

8


Not possible with CSS adjust the video, because the video is in an Iframe, so use width: who will adjust is Iframe, the only way I think will work is to use the Youtube API Iframe

An example using only the Youtube API, needlessly use entire external libraries such as jQuery and needlessly of plugins, each video will have to look like this:

<div data-youtube="[ID DO VIDEO DO YOUTUBE]" id="[ID opcional, não pode repetir]"></div>

<div data-youtube="[ID DO VIDEO DO YOUTUBE]"></div> <!-- sem id -->

<div data-youtube="[ID DO VIDEO DO YOUTUBE]" id="[ID opcional, não pode repetir]"></div>

Then with the native Javascript functions:

  • Htmlelement.dataset
  • querySelectorAll
  • addEventeListner to use with Window resize

I created this example:

The id="" is now optional, if there is no id an id will be generated in this format: id="youtube-responsive-x" (the x will be a number)

<!-- sem id -->
<div data-youtube="M7lc1UVf-VE"></div>

<hr>

<!-- com id -->
<div data-youtube="TALH8SsQJp4" id="baz"></div>

<script>
(function (w, d) {
    var iframes = [], genericIds = 0;

    function responsiveIframe(element)
    {
        var originalWidth = element.dataset.youtubeWidth || element.clientWidth;
        var originalHeight = element.dataset.youtubeHeight || element.clientHeight;

        element.dataset.youtubeWidth = originalWidth;
        element.dataset.youtubeHeight = originalHeight;

        element.width = "100%";

        if (originalWidth != originalHeight) {
            element.height = element.clientWidth / (originalWidth / originalHeight);
        } else {
            element.height = element.clientWidth;
        }
    }

    function putPlayer(youtubeId, elementId)
    {
        var player = new YT.Player(elementId, {
            videoId: youtubeId,
            events: {
                onReady: function() {
                    var el = d.getElementById(elementId);
                    responsiveIframe(el);
                    iframes.push(el);
                }
            }
        });
    }

    w.onYouTubeIframeAPIReady = function ()
    {
        //Busca todos elementos com o atributo data-youtube (tem que ter "id")
        var els = d.querySelectorAll("[data-youtube]");

        for (var i = 0, j = els.length; i < j; i++) {
            var el = els[i];

            if (!el.id) {
                genericIds++; //Incrementa para usar nos elementos sem ID
                el.id = "youtube-responsive-" + genericIds;
            }

            putPlayer(el.dataset.youtube, el.id);
        }

        w.addEventListener("resize", function() {
            if (iframes.length) {
                for (var i = 0, j = iframes.length; i < j; i++) {
                    responsiveIframe(iframes[i]);
                }
            }
        });
    };

    //Injeta a API do Youtube
    var tag = d.createElement("script");
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = d.getElementsByTagName("script")[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
})(window, document);
</script>

Example in Jsfiddle

Note: I didn’t use Stack Snippet because it uses Sandbox and the Youtube API doesn’t work in Sandbox

  • in which case all my life I am posted an article with video, I will have to put a div with a different id?

  • Please man can do, I really need your help

  • It worked perfectly, but with the issue of the Youtube API on div, I would put the attributes of Embed, because I don’t want it to appear, videos related to finishing my video, or the title of the video because you can click and leave my site, and my interest is her sailing. Can solve more this genius issue @guilhermeNascimento

  • Something happened, not that it is a problem, the script even works, Responsive and tals, but if you open it on the screen of the cell phone is not responsive but only on the screen of the computer, see - http://maroclub.net/cardapio-completo-para-perder-6kg-in-15-days/ on this link you open and can even decrease the screen q it will be responsive, but if open directly in the resolution of the mobile phone it does not fit

  • Moto G, android 6.0, also tested on pc, decreasing the window on google Chrome and then updating.

  • Look? In case you’re trying to warn me

  • @Gersonvaldeir worked in Browser (native) and Chrome and worked normally in both, you opened the jsfiddle on your mobile, or you created a page, if you created a page can be another script of yours that conflicted with this.

  • I use the wordpress platform, can help me ? I really need to adjust my iframes to responsive, http://maroclub.net

  • Yes it is, it is possible to do it yes

  • Just don’t change Divs name or other elements because I can end the entire site, so what I can do is implement either js, css or html

  • Not that I know, understand the basics, I know it works on Youtube works

  • @Gersonvaldeir the part of the vars, to take out the related I am solving, as soon as possible I send you.

  • Okay you’re the guy, helping me a lot

  • @Gersonvaldeir tests this and see if it works on your android: https://github.com/brcontainer/responsive-youtube.js

  • Please avoid long discussions in the comments; your talk was moved to the chat

  • @Guilhermenascimento This example uses with your code ?

  • @Gersonvaldeir this link I sent you was the same code of the question, but improved, the link is mine a lib too, can use quietly, if you miss something let me know. There is only one small difference, this new one I made (no link) has backward compatibility with some older browsers.

  • @Guilhermenascimento I tried but could not, could please put the example, updated and complete in another answer if it is not bother!

  • @Gersonvaldeir so it’s a bit busy for me, but I’ll create an online example and send you the link as soon as I can, so just open the link on mobile.

  • Dude I don’t even know how to thank you....

Show 15 more comments

5

Take a look at this javascript/Jquery library, it’s used for responsive videos:

http://fitvidsjs.com/

https://github.com/davatron5000/FitVids.js

Only search about fitvids.

For 100% video you add an advanced "iframe[src*="youtube selector to css".

$(document).ready(function(){
    // Target your .container, .wrapper, .post, etc.
   $(".conteudo").fitVids();
});
.conteudo{
  background-color:#f1f1f1;
  width:100%;
  height:100%;
  max-width:100%;
  max-height:100%;
}
iframe[src*="youtube"] {
  width:100%;
  height:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fitvids/1.2.0/jquery.fitvids.min.js"></script>
<body>
  <div class="conteudo">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/-ljBNAt2gwc" frameborder="0" allowfullscreen></iframe>
  </div>
</body>

  • Put but didn’t work, Put in <head> might not work ? both jQuery and Css didn’t work

  • usually scripts like fitvids I put in the footer, at the bottom, in the example above, but you can put in the head, only iframes that are inside the div with the class "content".

  • I work with Wordpress, I opened the site’s posts area to search with Inspect element, but there are several Divs and I put some but it didn’t work. can give me a hand, open the site and look at the post area, in inspect Element, see if you can identify div with content class.

  • plays that code $( '.entry-content' ).fitVids(); instead of $(".content"). fitVids();

  • I tried that class too but it didn’t work :(

  • If you observe wordpress leaves the <iframe> inside another tag, <p> adds automatic, you need to reference it too ?

  • no need, fitvids already applied, just left to leave the width 100%, and set a heigth, in case it will have to be manual, or you can use the example below, it adapted the iframe in a very cool way

Show 2 more comments

4

Using the fitVids library, you should select via jquery the parent element of the iframe that will be responsive.

In the documentation it is possible to obtain more details of use, such as ignoring some elements or selecting specific elements: https://github.com/davatron5000/FitVids.js

In your code you should import the Fitvids.js library and add a line of code.

$(".conteudo").fitVids();
.conteudo{
  background-color:#f1f1f1;
  width:700px;
  height:700px;
  padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fitvids/1.2.0/jquery.fitvids.min.js"></script>
<body>
  <div class="conteudo">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/-ljBNAt2gwc" frameborder="0" allowfullscreen></iframe>
  </div>
</body>

1

There are two ways to do this with CSS.

One is doing the iframe Youtube occupy the entire screen, the other and use a Hake with padding to do the iframe maintain the Aspect-ratio.

Placing the iframe with 100% height and width, without distorting the video, or leaving black bands on the side. For this we needed to use @media (min-aspect-ratio: 16/9) and @media (max-aspect-ratio: 16/9) to control behavior.

inserir a descrição da imagem aqui

Follow the image code above

html, body {
	width: 100%;
	height: 100%;
	margin: 0;
	padding: 0;
}
iframe {
	width: auto;
	height: auto;
	min-width: 100%;
	min-height: 100%;
	display: block;
}
@media (min-aspect-ratio: 16/9) {
  iframe {
    width: 100%;
	height: auto;
  }
}
@media (max-aspect-ratio: 16/9) {
  iframe {
    width: auto;
	height: 100%;
  }
}
<iframe src="https://www.youtube.com/embed/WHPEKLQID4U" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Option to keep Aspect-ratio with Hake of padding

The padding of the element is relative to its width, and can be used in percentage, so we can have a .box 100% wide and a padding-top that will "force" the height of the box to maintain a measure of Aspect-ratio.

inserir a descrição da imagem aqui

To know the value of this padding-top we have to know the proportion of the video. By default Youtube uses 9/16. So we take 9 divide by 16 and multiply by 100 and we have the value of 56,25% that is ours Aspect-ratio that we will use in the value of padding

inserir a descrição da imagem aqui

If you have a video 3 / 4 = 0,75 > * 100 = 75%. So in css you put in .box the padding-top: 75% and so you will keep the Aspect-ratio video. With this technique you need an element to put the video in, not to apply directly to iframe, because in that iframe will be 100% the size of .box, which in turn is the container that will keep the look of the video that is inside it.

Follow the image code above

html, body {
	width: 100%;
	height: 100%;
	margin: 0;
	padding: 0;
}

.box {
	width: 100%;
	padding-top: 56.25%;
	position: relative;
}
.box iframe {
	width: 100%;
	height: 100%;
	position: absolute;
	top: 0;
	left: 0;
}
<div class="box"><iframe src="https://www.youtube.com/embed/WHPEKLQID4U" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>


TIP

Recommended reading to understand the Aspect-ratio:
https://mdooh.progic.com.br/aspect-ratio/

Calculator of Aspect-ratio:
https://calculateaspectratio.com/

Documentation by Mozilla about Aspect-ratio:
https://developer.mozilla.org/en-US/docs/Web/CSS/@media/Aspect-ratio

Browser other questions tagged

You are not signed in. Login or sign up in order to post.