How can I make the YouTube player scale to the width of the page but also keep the aspect ratio?

后端 未结 14 1925
一向
一向 2021-01-30 11:09

I have a YouTube video I want to put on my web page.

I want to scale the video to fit to a percent of the users browser but also to keep the aspect ratio.

I hav

14条回答
  •  别那么骄傲
    2021-01-30 11:24

    I hit a similar issue with my site when developing some responsive CSS. I wanted any embedded Youtube objects to resize, with aspect, when switching from the desktop CSS to something smaller (I use media queries to re-render content for mobile devices).

    The solution I settled on was CSS and mark-up based. Basically, I have three video classes in my CSS thus:

    .video640 {width: 640px; height: 385px}
    .video560 {width: 560px; height: 340px}
    .video480 {width: 480px; height: 385px}
    

    … and I assign one of these to the Youtube content I include, depending on its original size (you may need more classes, I just picked the most common sizes).

    In the media query CSS for smaller devices, these same classes are simply re-stated like so:

    .video640 {width: 230px; height: 197px}
    .video560 {width: 230px; height: 170px}
    .video480 {width: 240px; height: 193px}
    

    I appreciate this requires some mark-up "up-front" when including videos in your HTML (i.e. adding a class), but if you don't want to go down the Javascript route, this works pretty well -- you could re-state your video classes for as many different sizes as you require. Here's how the Youtube mark-up looks:

    
      
    
    

提交回复
热议问题