Html5 video background, keep center of video in center

后端 未结 10 1359
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-23 12:00

I am trying to keep a background video centered regardless of how big the user drags the video. It\'s currently cutting off the right side of the videos when i scroll smalle

相关标签:
10条回答
  • 2020-12-23 12:28

    This is much shorter and worked for me.

    video {
        position: fixed;
        right: 0;
        bottom: 0;
        min-width: 100%;
        min-height: 100%;
        transform: translateX(calc((100% - 100vw) / 2));
    }
    
    0 讨论(0)
  • 2020-12-23 12:33

    In my use case where I always wanted the video to cover the entire viewport (no matter if the viewport aspect ratio was bigger or lower than the videos), the above solution didn't work exactly how i intended. Instead, the following worked much better:

    .video-container {
      position: absolute;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
    }
    .video-container > video {
      display: block;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      z-index: 1;
    }
    @media screen and (max-aspect-ratio: 1920/1080) {
      .video-container > video {
        height: 100%;
      }
    }
    @media screen and (min-aspect-ratio: 1920/1080) {
      .video-container > video {
        width: 100%;
      }
    }
    

    My video was 1920x1080, and this works in IE11 (didnt test lower) and beyond.

    0 讨论(0)
  • 2020-12-23 12:33

    So I tested above solutions and couldn't find that one, so here is mine:

    video {
          position: fixed;
          left: 50%;
          top: 50%;
          min-width: 100%;
          min-height: 100%;
          transform: translate(50%, -50%);
    }
    
    0 讨论(0)
  • 2020-12-23 12:35

    Use object-fit: cover;

    video {
      position: absolute;
      right: 0;
      bottom: 0;
      height: 100vh;
      width: 100vw;
      object-fit: cover;
    }
    
    0 讨论(0)
提交回复
热议问题