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

背景英雄视频无法自适应调整大小问题求助

视频背景无法自适应容器的解决方法

问题根源

你的代码里存在类名不匹配的错误:CSS中定义的容器类是.hero-section,但HTML里的div用的是hero section(两个独立类),导致容器的position: relative、height等关键样式根本没生效,视频自然无法相对于容器自适应。

修正步骤

  1. 修正HTML容器的类名,把class='hero section'改为class='hero-section',让CSS样式能正确作用到容器上。
  2. 确保视频的object-fit: cover属性生效,这个属性会让视频保持比例的同时铺满容器,不会变形。

修正后的完整代码

CSS代码

body {
    margin: 0;
}

.hero-section {
    position: relative;
    height: 85vh;
    width: 100%;
    display: grid;
    place-content: center;
    overflow: hidden; /* 防止视频超出容器,避免出现滚动条 */
}

video{
    position: absolute;
    object-fit: cover;
    width: 100%;
    height: 100%;
    z-index: -1;
    top: 0; /* 确保视频从容器顶部开始定位 */
    left: 0; /* 确保视频从容器左侧开始定位 */
}

@media screen and (min-width: 900px) {
    .hero-section {
        height: 100vh;
    }
}

HTML代码

<!DOCTYPE html>
<html>
    <head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Document</title>
    <link rel='stylesheet' href='styles.css'>
    </head>

    <body>
    <div class='hero-section'>
        <video autoplay muted loop playinline src='images/uhoh.mp4'></video>
    </div>
    </body>
</html>

额外说明

  • 若希望完整显示视频(允许容器边缘留黑边),可把object-fit: cover换成object-fit: contain。
  • 给.hero-section加overflow: hidden是为了避免视频超出容器时出现滚动条,提升页面观感。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 06:05:20