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

后端 未结 14 1910
一向
一向 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:29

    What i believe to be the best CSS solution.

    .auto-resizable-iframe {
      max-width: 420px;
      margin: 0px auto;
    }
    
    .auto-resizable-iframe > div {
      position: relative;
      padding-bottom: 75%;
      height: 0px;
    }
    
    .auto-resizable-iframe iframe {
      position: absolute;
      top: 0px;
      left: 0px;
      width: 100%;
      height: 100%;
    }
    
    <div class="auto-resizable-iframe">
      <div>
        <iframe frameborder="0" allowfullscreen="" src="http://www.youtube.com/embed/_OBlgSz8sSM"></iframe>
      </div>
    </div>
    

    Demo http://jsfiddle.net/JBhp2/

    0 讨论(0)
  • 2021-01-30 11:35

    There are a few suggestions on the list of answers to use js to modify the structure of generated iframe. I think there is a risk with that because when you wrap the iframe inside other elements it's possible that the YouTube API will lose 'connection' with the iframe (especially if you pass the element in as a node instead of using specific id like me). It's rather to get around it actually, use javascript to modify the content before you actually trigger the youtube player.

    a snippet from my code:

    /**
     * Given the player container, we will generate a new structure like this
     *
     * <div class="this-is-the-container">
     *      <div class="video-player">
     *          <div class="auto-resizable-iframe">
     *              <div>
     *                  <iframe frameborder="0" allowfullscreen="" src="http://www.youtube.com/embed/_OBlgSz8sSM">        </iframe>
     *              </div>
     *          </div>
     *      </div>
     * </div>
     *
     * @return {Node} the real player node deep inside
     */
    YouTube.renderResizable = function (playerContainer) {
        // clean up the content of player container
        playerContainer.textContent = '';
    
        var playerDiv = document.createElement('div');
        playerDiv.setAttribute('class', 'video-player');
    
        playerContainer.appendChild(playerDiv);
    
        // add the auto-resizable-frame-div
        var resizeableDiv = document.createElement('div');
        resizeableDiv.setAttribute('class', 'auto-resizable-iframe');
    
        playerDiv.appendChild(resizeableDiv);
    
        // create the empty div
        var div = document.createElement('div');
        resizeableDiv.appendChild(div);
    
        // create the real player
        var player = document.createElement('div');
        div.appendChild(player);
    
        return player;
    };
    
    0 讨论(0)
提交回复
热议问题