DEV Community

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

Posted on • Updated 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

Top comments (0)