It is not possible with CSS to adjust the video, because the video is in an Iframe, so if you use width:
it will adjust iframe, the only way I think it will work is to use Youtube API Iframe
An example using only the Youtube API, without needing to use entire external libraries like jQuery and no need for plugins, each video will have to look like this: p>
<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>
So with the native JavaScript functions:
- HTMLElement.dataset
- querySelectorAll
- addEventeListner to use with Window resize
I've created this example:
The id=""
is now optional, if not id will be generated an id in this format: id="youtube-responsive-x"
( 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 on Jsfiddle
Note: I did not use Stack Snippet because it uses Sandbox and the Youtube API does not work in Sandbox