How to Create Responsive YouTube Video Embeds
When embedding YouTube videos on your website, one common issue is that they are displayed as iframes
which require a specific height and width. This can cause problems, especially when viewing the video on mobile devices. The key is to make the video responsive, allowing it to scale down accordingly.
To achieve a responsive YouTube video embed, follow these steps:
- Wrap the YouTube video in a container
div
:
1 | <div class="video-container"> |
- Apply the following CSS to your website:
1 | .video-container { |
The CSS code is responsible for making the video responsive by maintaining its aspect ratio.
The video-container
class is used to set the container’s dimensions, ensuring that it takes up the full width of its parent element.
The video-container::after
pseudo-element is used to create a placeholder with a percentage-based padding. In this case, 56.25%
is the padding needed for a video with a 16:9 aspect ratio. If your video has a different aspect ratio, adjust this value accordingly.
The video-container iframe
selector positions the iframe
element absolutely within the container, filling up the available space.
By implementing the above steps, your YouTube videos will now be displayed in a responsive manner, scaling down appropriately for different devices.
Remember to adjust the padding percentage based on the aspect ratio of your video. For example, if your video has a 4:3 aspect ratio, set the padding to 75%.
Tags: responsive design, YouTube video, embedding videos, CSS, aspect ratio