Embedding YouTube Videos in Blog Posts
• 2 min read
One of the powerful features of MDX is the ability to embed rich media content like YouTube videos directly in your blog posts. This makes it easy to create engaging, multimedia content.
Embedding a YouTube Video
Below is an example of an embedded YouTube video. The video is fully responsive and will adapt to different screen sizes.
How It Works
The video is embedded using a responsive iframe wrapper. The key CSS properties are:
padding-bottom: 56.25%- This creates a 16:9 aspect ratio (9/16 = 0.5625)position: relative- Allows absolute positioning of the iframe insideposition: absoluteon the iframe - Makes it fill the containerwidth: 100%andheight: 100%- Ensures the video fills the space
YouTube Embed URL Format
To embed a YouTube video, convert the watch URL to an embed URL:
- Watch URL:
https://www.youtube.com/watch?v=gkzh3z3jKdw - Embed URL:
https://www.youtube.com/embed/gkzh3z3jKdw
Simply replace /watch?v= with /embed/.
Additional Options
You can add query parameters to customize the embed:
<!-- Start at a specific time (in seconds) -->
<iframe src="https://www.youtube.com/embed/gkzh3z3jKdw?start=30"></iframe>
<!-- Disable related videos at the end -->
<iframe src="https://www.youtube.com/embed/gkzh3z3jKdw?rel=0"></iframe>
<!-- Autoplay (note: most browsers require muted for autoplay) -->
<iframe src="https://www.youtube.com/embed/gkzh3z3jKdw?autoplay=1&mute=1"></iframe>
Creating a Reusable Component
For better reusability, you could create a YouTube component:
// src/components/YouTube.astro
---
interface Props {
videoId: string;
title?: string;
}
const { videoId, title = "YouTube video player" } = Astro.props;
---
<div class="video-container">
<iframe
src={`https://www.youtube.com/embed/${videoId}`}
title={title}
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
</div>
<style>
.video-container {
position: relative;
padding-bottom: 56.25%;
height: 0;
overflow: hidden;
max-width: 100%;
margin: 2rem 0;
}
.video-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
Then use it in your MDX like this:
import YouTube from '../../components/YouTube.astro';
<YouTube videoId="gkzh3z3jKdw" title="My awesome video" />
This keeps your content clean and makes it easy to embed videos throughout your blog!