How to Embed YouTube Videos with Correct Aspect Ratio
If you’ve ever tried to embed a YouTube video on your website, you may have encountered difficulties in setting the correct aspect ratio, especially when dealing with fluid layouts. In this article, I will share with you the solution I found to embed YouTube videos with the correct aspect ratio.
Using Tailwind code with React
For those using Tailwind code with React, you can achieve the desired result with the following code:
1 | <iframe className="aspect-video w-full" src={"YouTube embed URL"}></iframe> |
Using Tailwind code without React
If you are not using React, you can still achieve the correct aspect ratio by using the following Tailwind code:
1 | <iframe class="aspect-video w-full" src="YouTube embed URL"></iframe> |
Using plain HTML and CSS
If you prefer not to use any frameworks, you can achieve the desired result using plain HTML and CSS:
1 | <iframe style="aspect-ratio: 16 / 9; width: 100%" src="YouTube embed URL"></iframe> |
Please note that the “YouTube embed URL” should be replaced with the actual URL of the YouTube video you want to embed. You can obtain this URL by replacing https://www.youtube.com/watch?v=
with https://www.youtube.com/embed/
in the video URL.
The absolute/relative trick (Obsolete)
In the past, some tutorials suggested using the absolute/relative trick to achieve the correct aspect ratio. However, this method is now considered obsolete and not recommended. Here is an example of how it used to be done:
1 | <style> |
I hope this article has helped you embed YouTube videos with the correct aspect ratio. Using the aspect-ratio
property is a simpler and more reliable approach compared to the obsolete absolute/relative trick.
Tags: YouTube, video embedding, aspect ratio, HTML, CSS, Tailwind, React