如何在保持响应的同时将YouTube视频居中?

问题描述 投票:0回答:3

我正在为我的游戏的目标网页制作移动版本。我有一个youtube预告片,它应该根据网站大小进行扩展,同时保持居中。但事实并非如此。您可以通过缩小浏览器大小来在我的网站http://www.zatackaonline.net上看到自己。

我尝试使用我在StackOverflow上的另一篇文章中找到的代码。这段代码将填满我不想要的整个屏幕。有什么方法可以将它缩小到50%的大小,同时保持嵌入的iFrame视频位置居中?

/*main.css*/

.video-container { 
position: relative; /* keeps the aspect ratio */ 
padding-bottom: 56%; /* fine tunes the video positioning */ 
padding-top: 60px; 
overflow: hidden;
}

.video-container iframe,
.video-container object,
.video-container embed { position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;

}
javascript html css youtube
3个回答
2
投票

首先,要在不更改代码的情况下将iframe设置为正确的宽度,可以使用vw单元(这里是视口单元上的some info):

#contentframe iframe{
    width:50vw;
}

其次,要使容器居中,请将margin-leftmargin-right值设置为auto,并指定其宽度:

#contentframe{
    /* left:294px */ // REMOVE
    width: 50vw;
    margin-left:auto;
    margin-right:auto;
}

请记住将所有这些包装在正确的媒体查询中,它应该可以做到!

编辑关于left:294px:我发现在响应式网站中尝试使用这些绝对值时会感到困惑,也许尽可能使用百分比值会让事情变得更容易。

编辑2这是一个工作小提琴:http://jsfiddle.net/EB57H/1/

编辑3 要在调整大小时保持比率,请从width源中删除heightiframe属性:http://jsfiddle.net/EB57H/2/

<iframe width=560" height="315" src="...
// BECOMES
<iframe src="...

这不太好用,这是another not very elegant solution


1
投票

代替 :

left:594px;

使用 :

text-align:center;

contentframe css风格

对于响应大小,从<iframe>中删除高度和宽度,并将css规则width:80%添加到iframe


0
投票

我将所有答案混合在一起,构建了一个优化的解决方案,具有中心,响应和最大高度,以避免视频在宽屏幕上占据所有页面。

CSS:

.video-container {
  width: 70vw;
  max-width: 560px ;
  margin:auto;
}

.video-container iframe,
.video-container object,
.video-container embed {
  width: 70vw;
  max-width: 560px ;
  height:calc((9/16)*70vw);
  max-height:calc((9/16)*560px);
}

HTML:

  <div class="video-container">
    <iframe
      width="853"
      height="480"
      src="https://www.youtube.com/embed/4JkIs37a2JE"
      frameborder="0"
      allowfullscreen
    ></iframe>
  </div>
© www.soinside.com 2019 - 2024. All rights reserved.