AI Workshop: learn to build apps with AI →
CSS Tips: How to embed YouTube videos using the correct aspect ratio

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


I had this problem.

I wanted to embed a YouTube video in a page, but since you need to use an iframe I couldn’t figure out how to properly set the height and width for it, in a way that would work on a fluid layout.

After a while I found the solution.

Tailwind with React:

<iframe className="aspect-video w-full"
  src={"YouTube embed URL"}>
</iframe>

Tailwind without React:

<iframe class="aspect-video w-full"
		    src="YouTube embed URL">
</iframe>

Plain HTML and CSS:

<iframe style="aspect-ratio: 16 / 9; width: 100%"
  src="YouTube embed URL"></iframe>

The YouTube embed URL looks like:

https://www.youtube.com/embed/VIDEO_ID

So if you have the video URL, you need to transform it, for example with:

videoUrl.replace('https://www.youtube.com/watch?v=', 
  'https://www.youtube.com/embed/')

Some old tutorials still list the absolute/relative trick, like this:

<style>
.videocontainer {
	position:relative; 
	padding-bottom:56.25%;
}
.videocontainer iframe {
	width:100%;
	height:100%;
	position:absolute;
}
</style>

<div class="videocontainer">
  <iframe src="YouTube embed URL"></iframe>
</div>

I prefer the simpler aspect-ratio property.

Lessons in this unit:

0: Introduction
1: How to center an element with CSS
2: CSS Border inside the element
3: What are good CSS Breakpoint values for Responsive Design?
4: How to debug CSS by bisecting
5: How to disable text selection using CSS
6: How to put an item at the bottom of its container using CSS
7: CSS, how to select elements that do not have a class
8: How to stick an element on the bottom of the page with flexbox
9: How to apply padding to multiple lines in CSS
10: Making a table responsive using CSS
11: CSS url()
12: How to make an element smaller or bigger with CSS
13: Customizing visited links
14: Fix extra space after inline element
15: How to create a sidebar that’s sticky but also scrolls
16: ▶︎ How to embed YouTube videos using the correct aspect ratio
17: Responsive pre tags in CSS
18: Responsive YouTube Video Embeds
19: How to remove all CSS from a page at once
20: How I added Dark Mode to my website
21: How to add a simple dark mode