如何将嵌入的Youtube视频居中,然后保持居中而不是整个屏幕宽度

时间:2017-01-25 11:01:17

标签: css html5 youtube

在Youtube中,嵌入视频的html格式为

    <iframe width="560" height="315" src="https://www.youtube.com/embed/6Es-eaG4xPg" 
frameborder="0" allowfullscreen></iframe>

但当然尝试使页面移动兼容时,屏幕尺寸小于560时会出现问题。

所以我将代码更改为

 <iframe class="screencast" src="https://www.youtube.com/embed/6Es-eaG4xPg" 
frameborder="0" allowfullscreen></iframe>

并且在样式表中有

.screencast {
     width=560
     height=315
}

我的想法是,我可以为不同的媒体宽度设置不同的部分

@media screen and (min-width:300px) and (max-width: 499px) {
    .screencast {
         width=280
         height=158
    }

但这根本没有影响,现在屏幕上显示的视频总是太小而且它的大小从未改变过它似乎忽略了css类

然后我发现了这个问题

Shrink a YouTube video to responsive width

需要在框架周围添加div

e.g

<div class="videowrapper">
<iframe src="https://www.youtube.com/embed/9Cf_xEbUzqE" n allowfullscreen></iframe>
</div>

然后将其添加到css

.videowrapper {
      margin:auto
      float: none;
      clear: both;
      position: relative;
      padding-bottom: 56.25%;
      padding-top: 25px;
      height: 0;
  }
  .videowrapper iframe {
      position: absolute;
      width: 100%;
      height: 100%;
  }

除非它使视频占据我不想要的全宽,否则我可以更改宽度

e.g

  .videowrapper iframe {
      position: absolute;
      width: 50%;
      height: 50%;
  }

并且除了水平居中视频

之外还有效

我尝试过各种各样的事情,比如

  .videowrapper iframe {
      position: absolute;
      left: 25%
      width: 50%;
      height: 50%;
  }

但我所做的一切都没有将图像集中在一起,我怎么能解决这个问题,为什么我在iframe上放一个类的简单方法没有任何效果。

1 个答案:

答案 0 :(得分:0)

您可以使用此代码

.video_center iframe{ margin: 0 auto; display:table; }