【问题标题】:HTML background video adjust to screen size that is responsiveHTML 背景视频调整为响应式屏幕大小
【发布时间】:2017-05-03 17:31:12
【问题描述】:

我的 HTML 背景视频有问题。 我在 Stack Overflow 上找到了一些文章,并将其添加到我的 HTML 和 CSS 中。 但它似乎不起作用,它要么无法响应,要么与我的其他 div 和元素混淆。

我有一张图片: (视频元素的容器背景颜色为黄色)

这里是代码:

.container {
   position: absolute;
   top: 0;
   bottom: 0;
   width: 100%;
   height: 100%;
   overflow: hidden;
   box-shadow:  0px 10px 24px 0px rgba(50, 50, 75, 0.49);
   font-size: 0;
   background-color: yellow;
   margin: auto;
   z-index: -1000;
}

.container video {
   min-width: 100%;
   min-height: 100%;

   width: auto;

   position: absolute;

   height: auto;
   max-height: 100%;
   width: 100%;
}

如您所见,视频宽度不会根据屏幕尺寸进行调整。我试过object-fit,但这会使其没有响应。

【问题讨论】:

    标签: html css video background responsive


    【解决方案1】:

    诀窍是让您的容器height: 0,然后在容器上应用视频的纵横比为padding-bottom。您可以通过将高度除以宽度并乘以 100 来获得一个百分比值,从而获得视频的纵横比。然后定位您的视频以占用容器中的整个空间。

    我示例中的视频是 320x176。 (176 / 320) * 100 = 55%。

    * {margin:0;}
    .container {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
      height: 0;
      overflow: hidden;
      box-shadow: 0px 10px 24px 0px rgba(50, 50, 75, 0.49);
      font-size: 0;
      background-color: yellow;
      margin: auto;
      z-index: -1000;
      padding-bottom: 55%;
    }
    
    .container video {
      position: absolute;
      top: 0; left: 0;
      width: 100%;
      height: 100%;
    }
    <div class="container">
      <video src="https://www.w3schools.com/html/mov_bbb.mp4" loop autoplay></video>
    </div>

    【讨论】:

    • 您好,谢谢您的回复。我试过这个,但它一直显示左右容器的背景(黄色)。我玩了一下,这对我来说起到了作用,就是给视频一个对象匹配的 css 规则:填充;
    • @RicardoHagens 我的演示是否如您所愿? object-fit 很棒,但它的浏览器支持很差。
    • 嗨迈克尔,很抱歉回复晚了,感谢 2019 年的提示!得到了我想要的修复,所以我对 StackOverflow 的关注消失了。
    【解决方案2】:

    如果您希望视频始终填充容器的 100% 宽度和 100% 高度,无论比例如何,那么您应该使用overflow:hidden,并使用位置 top,right,bottom,left 属性如果你想把它居中。

    .container .video{
        min-width:100%;
        min-height:100%;
        overflow:hidden;
    }
    

    【讨论】:

      【解决方案3】:

      这对我来说至少达到了我对桌面的期望:

      .container{
          width: auto;
          height: 100%;
          position: absolute;
      
        bottom: 0px;
        top: 0px;
        background-color: yellow;
        z-index: -1000;
        overflow: hidden;
        box-shadow:  0px 10px 24px 0px rgba(50, 50, 75, 0.49);
      
        margin: auto;
      
        font-size: 0;
      }
      
      
      .container video{
      
          min-width: 100%;
          min-height: 100%;
         position: static;
          top: 0;
          left:0;
         height: 100%;
         width: 100%;
         object-fit: fill;
      
        }
      

      对于移动设备,我会给它一个不同的规则,因为现在视频会改变纵横比(这是我想要的)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-17
        • 1970-01-01
        • 1970-01-01
        • 2015-04-09
        • 2019-10-14
        • 2016-07-03
        相关资源
        最近更新 更多