如何实现宽度100%/100vw、高度100vh的背景视频?保持比例不拉伸可裁剪
实现全屏背景视频(保持原比例,允许裁剪)
Got it, I’ve tackled this exact scenario countless times for client projects—here’s a clean, battle-tested solution that checks all your boxes:
HTML 结构
First, set up your video element with necessary attributes (plus a fallback image for cases where video can’t load):
<video class="background-video" muted autoplay loop playsinline> <source src="your-video-file.mp4" type="video/mp4"> <!-- Fallback for browsers that don't support video or failed loading --> <img src="fallback-background.jpg" alt="Background fallback"> </video>
The muted, autoplay, and loop are standard for background videos (browsers block autoplay with sound by default). playsinline fixes playback glitches on iOS devices.
CSS 核心样式
This is where we ensure the video fills the viewport without distortion, cropping only what’s necessary:
.background-video { /* Lock the video to cover the entire viewport */ position: fixed; top: 0; left: 0; /* Force the video to stretch to full viewport dimensions */ width: 100vw; height: 100vh; /* Critical: Preserve original aspect ratio, crop excess to fit */ object-fit: cover; /* Send video to the background so your content sits on top */ z-index: -1; /* Optional: Ensure cropping happens from the center (keeps key content visible) */ object-position: center center; }
关键属性拆解
position: fixed: Keeps the video anchored in place so it doesn’t scroll with page content (swap toabsoluteif you need it confined to a specific container instead of full viewport).width: 100vw/height: 100vh: Guarantees the video stretches to the full width and height of the user’s screen.object-fit: cover: This is the star property—it scales the video to maintain its original aspect ratio, automatically cropping any parts that don’t fit within the 100vw/100vh bounds (exactly what you requested: no distortion, allowed cropping).object-position: center center: Ensures the cropping happens from the middle of the video, so the most important visual content stays front and center.
额外优化小贴士
- If you need the video inside a specific container (not full viewport), replace
100vw/100vhwith100%and set the parent container toposition: relativewith definedwidth/height. - For legacy browsers like IE11 that don’t support
object-fit, you can use a lightweight JS polyfill—but most modern projects skip this since IE usage is now negligible. - Always optimize your video file (compress it to a reasonable size, use modern codecs like H.265) to avoid slow page loads.
内容的提问来源于stack exchange,提问作者Vitaly Zalivan
相关产品推荐
相关产品推荐

