将youtube视频垂直居中于容器中

时间:2016-10-05 09:38:05

标签: html css iframe

我有一个响应式Youtube视频,我把它放在一个最大高度的容器中。视频在底部裁剪。有没有办法平均裁剪顶部和底部,以便视频在容器内垂直居中,播放按钮位于中间?

JS小提琴: https://jsfiddle.net/3qtawjb7/

Address Publisher::getAddress(){
    return a;
}


Publisher Book::getPublisher(){
    return d;
}
void Address::set(string value , int number){
switch(number)
{
    case STREET_NUMBER:
        streetNumber = value;break;
    case STREET_NAME:
        streetName = value;break;
    case CITY:
        city = value;break;
    case COUNTRY:
        country = value;break;
    case POSTAL_CODE:
        postalCode = value;break;


  }
}
.video-outer {
  max-height: 200px;
  overflow: hidden;
  position: relative;
}
.video-container {
  position: relative;
  padding-bottom: 56.25%;
  height: 0;
}
.video-container iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  max-width: 100%;
}

3 个答案:

答案 0 :(得分:0)

应该像这样工作:

.video-outer {
  height: 100vh;
  overflow: hidden;
  position: relative;
}

.video-container {
  position: relative;
  height: 30%;        /* height has to be defined for my changes below*/
}

.video-container iframe {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  width: 100%;
  height: 100%;
  max-width: 100%;
}
<div class="video-outer">
  <div class="video-container">
    <iframe id="player" frameborder="0" allowfullscreen="1" title="YouTube video player" width="640" height="360" src="https://www.youtube.com/embed/feLDAys0v-c"></iframe>   		  </div>
</div>

答案 1 :(得分:0)

JS小提琴如何:https://jsfiddle.net/p74oz13c/

我删除了:

<div class="video-outer"> ... </div>
完全

...容器,然后添加:

padding-top: -50%;

...以.video-container样式。

答案 2 :(得分:0)

我最终编写了一个jQuery解决方案,因为建议的答案没有响应。

  // vertically center video in iframe

  function centerVideo() {
    // get height of container
    $containerHeight = $( '.video-outer' ).height();
    $containerWidth = $( '.video-outer' ).width();
    $containerRatio = 360/640;

    // get height of video
    $videoHeight = $containerWidth * $containerRatio;

    // position video in center
    $heightDiff = $containerHeight - $videoHeight;
    $heightDiff = Math.round($heightDiff/2) + "px";
    $( '.video-container' ).css( 'top', $heightDiff );
  }

  // execute on load
  centerVideo();

  // recalculate on browser resize
  jQuery( window ).resize(function() {
    centerVideo();
  });