You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复HTML+CSS网页背景视频无法全屏显示问题

解决视频背景左右留白的问题

我之前也碰到过一模一样的问题,折腾了好一会儿才搞明白关键在哪。咱们一步步来修复:

1. 清除页面默认边距

浏览器会给<html>和<body>标签加上默认的margin和padding,这是导致视频四周出现空白的常见原因之一。先把这个干掉:

html, body {
  margin: 0;
  padding: 0;
  overflow: hidden; /* 防止出现不必要的滚动条 */
}

2. 给视频容器设置相对定位

你的.video-overlay用了position: absolute,但它的父元素.blue没有设置position: relative,这会导致overlay相对于整个页面定位,可能干扰视频的布局。给.blue加上相对定位:

.blue {
  grid-column: 1/-1;
  height: 100vh;
  position: relative; /* 让子元素的绝对定位基于这个容器 */
}

3. 用object-fit: cover让视频完美覆盖容器

这是解决视频留白的核心!单纯设置width/height: 100%只会拉伸视频,要么变形要么留空白。object-fit: cover会让视频保持原比例,同时填满整个容器,超出部分自动裁剪,刚好满足全屏背景的需求。修改你的视频样式:

.video-background {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 关键属性 */
  position: absolute;
  top: 0;
  left: 0;
}

同时记得把HTML里video标签的内联width="100%" height="100vh"删掉,避免和CSS冲突。

修改后的完整代码

CSS部分:

html, body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.container { 
  background: rgba(0, 0, 0, 0.9); 
  text-align: center; 
  color: white; 
  font-size: 2em; 
  display: grid; 
  grid-template-columns: repeat(12, 1fr); 
  grid-gap: 0; 
}

/*Adjust container for Fullscreen Video Background*/
.blue { 
  grid-column: 1/-1; 
  height: 100vh; 
  position: relative;
}

.video-background {
  width: 100%;
  height: 100%;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
}

.video-overlay { 
  width: 100%; 
  height: 100vh; 
  position: absolute; 
  top: 0; 
  left: 0; 
  background: #000000; 
  z-index: 1; /* 调整z-index确保overlay在视频上方 */
  opacity: 0.75; 
}

/* 导航和标题的样式保持不变,记得给它们设置z-index高于overlay */
.navigation {
  position: relative;
  z-index: 2;
}

.title {
  position: relative;
  z-index: 2;
}

HTML部分(只修改video标签):

<video class="video-background" src="https://www.w3schools.com/howto/rain.mp4" autoplay muted loop>
</video>

这样改完之后,视频应该就能完美全屏覆盖,不会有左右空白了。另外注意给导航和标题设置更高的z-index,确保它们能显示在视频和overlay上方。

内容的提问来源于stack exchange,提问作者DeltaTroz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:32:14