DEV Community

Cover image for Easy way to embed responsive YouTube iframe
Rogerio Orioli
Rogerio Orioli

Posted on • Edited on

Easy way to embed responsive YouTube iframe

Use aspect-ratio CSS property

The aspect-ratio CSS property allows you to define the desired width-to-height ratio of an element's box. This means that even if the parent container or viewport size changes, the browser will adjust the element's dimensions to maintain the specified width-to-height ratio. The specified aspect ratio is used in the calculation of auto sizes and some other layout functions.

1 . Create the css rule in your respective css file

 .aspect-video {
     aspect-ratio: 16 / 9;
 }
Enter fullscreen mode Exit fullscreen mode

2 . Add this css class to class attribute in iframe tag and change value of attribute width to width="100%"

if you use Tailwind CSS in your project exist the same class called aspect-video.

See reference in link below
https://tailwindcss.com/docs/aspect-ratio#setting-the-aspect-ratio


 <iframe 
   class="aspect-video"
   width="100%"
   src="https://www.youtube.com/embed/" 
   allow="accelerometer; 
   autoplay; 
   clipboard-write; 
   encrypted-media; 
   gyroscope; 
   picture-in-picture;
   web-share fullscreen" 
   allowFullScreen
>
</iframe>

Enter fullscreen mode Exit fullscreen mode

REFERENCE : https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio
https://tailwindcss.com/docs/aspect-ratio#setting-the-aspect-ratio

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay