So here's a solution that I come up with with the help of JavaScript. The problem we have here is that the height cannot be determined without knowing the width and since the width is dynamic there is no way to hard code the height.
We can get the width of the element using JavaScript, with it, we can calculate the height using the aspect ratio of 16:9 for standard video. Of course, you can change the aspect ratio to something else but usually, YouTube video comes with the aspect ratio of 16:9.
This code will make the iframe full width according to its container. That means if the body is 100px and the container is 80px if the iframe is in the container the width will be 80px. There won't be going out of the container and mess up with the responsive design.
This code will resize the iframe every time the page is loaded or resized, making sure that it is always maintaining the 16:9 aspect ratio. Most people might be using a phone to view it and make sure it resizes when the phone move from vertical to horizontal might be important.
Here's how to do it:
window.addEventListener("load", playerSizer); /* Resize on load */
window.addEventListener("resize", playerSizer); /* Resize on change in window size */
/* Resize function */
function playerSizer() {
var player = document.getElementById("player"); /* Element ID */
var width = player.offsetWidth; /* Get width */
player.style.height = (width * 0.5625) + "px"; /* Aspect ratio */
}
<center>
<!-- Remember to change your YouTube URL -->
<!-- Note width="100%", this will be used to calculate height -->
<!-- Note id="player", this will be used by JavaScript function -->
<iframe
id="player"
width="100%"
src="YOUR URL"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
Your browser does not support this, try viewing it on YouTube: YOUR URL
</iframe>
</center>
Here's the code if you don't want to separate JavaScript with HTML:
<center>
<iframe id="player" width="100%" src="YOUR URL" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>Your browser does not support this, try viewing it on YouTube: YOUR URL</iframe>
</center>
<script>
window.addEventListener("load", playerSizer);
window.addEventListener("resize", playerSizer);
function playerSizer() {
var player = document.getElementById("player");
var width = player.offsetWidth;
player.style.height = (width * 0.5625) + "px";
}
</script>
Hope this helps 😉