Embedding YouTube videos into web pages is a common practice, but it's essential that the video adjusts correctly to various screen sizes. To achieve this, a responsive iframe can be used, ensuring that the video always looks good regardless of the device it's viewed on. Here's the code for a responsive YouTube iframe:
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
<iframe src="/" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0;" allowfullscreen></iframe>
</div>
How does this code work?
- The
<div>
container holds the iframe and sets the aspect ratio for responsiveness.
padding-bottom: 56.25%;
sets the aspect ratio (16:9), allowing the iframe to adjust to the container's width.
position: relative;
maintains the relative position of the container, which is important for the iframe's position.
position: absolute;
allows the iframe to fill the entire space within the container.
top: 0; left: 0;
aligns the iframe to the top-left corner of the container.
width: 100%; height: 100%;
ensures the iframe occupies all available space inside the container.
border: 0;
removes borders from the iframe.
allowfullscreen
enables fullscreen mode for the embedded YouTube content if supported.
This code allows you to embed a YouTube video on your web page in a way that automatically adapts to the screen size, ensuring a good user experience regardless of the device the video is viewed on.