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

如何用CSS background-image实现网站首屏全屏覆盖及滚动显示后续内容

嘿,我正好实现过类似的首屏全屏背景效果,给你一套直接能用的方案,完全匹配你想要的「首屏背景图全屏覆盖,后续内容滚动才出现」的需求:

完整实现代码

HTML 结构

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>首屏全屏背景示例</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <!-- 首屏全屏背景容器 -->
    <section class="hero">
        <!-- 可选:首屏上的文字内容,比如标题、引导按钮 -->
        <div class="hero-content">
            <h1>欢迎来到我的网站</h1>
            <p>向下滚动查看更多内容</p>
        </div>
    </section>

    <!-- 后续滚动才显示的内容 -->
    <section class="content">
        <h2>关于我们</h2>
        <p>这里是后续的网站内容,只有当用户向下滚动时才会出现在视图中...</p>
        <p>可以添加更多段落、图片或其他功能模块</p>
    </section>
</body>
</html>

CSS 样式

/* 重置默认样式,避免浏览器自带的margin/padding干扰布局 */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

/* 确保body至少占满整个视口高度,避免内容过短导致布局异常 */
body {
    min-height: 100vh;
    overflow-x: hidden;
    font-family: Arial, sans-serif;
}

/* 首屏背景容器核心样式 */
.hero {
    /* 占满当前浏览器视口的高度,实现**首屏全屏**效果 */
    height: 100vh;
    width: 100%;
    /* 替换成你的背景图片地址 */
    background-image: url('your-background-image.jpg');
    /* 让背景图按比例缩放,完全覆盖容器,无空白区域 */
    background-size: cover;
    /* 背景图居中对齐,优先展示图片核心区域 */
    background-position: center center;
    /* 禁止背景图重复平铺 */
    background-repeat: no-repeat;
    /* 用flex布局让内部文字垂直水平居中 */
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    /* 给文字加阴影,提升在背景图上的可读性 */
    color: white;
    text-shadow: 0 2px 4px rgba(0,0,0,0.8);
}

/* 首屏内容的自定义样式(可选) */
.hero-content h1 {
    font-size: 3rem;
    margin-bottom: 1rem;
}

.hero-content p {
    font-size: 1.2rem;
}

/* 后续内容区域样式 */
.content {
    /* 给内容添加内边距,避免贴边显示 */
    padding: 4rem 2rem;
    max-width: 1200px;
    margin: 0 auto;
}

.content h2 {
    font-size: 2rem;
    margin-bottom: 1.5rem;
    color: #333;
}

.content p {
    font-size: 1.1rem;
    line-height: 1.6;
    color: #555;
    margin-bottom: 1rem;
}
关键逻辑解释
  • height: 100vh:让.hero容器正好匹配当前浏览器视口高度,精准实现首屏全屏覆盖
  • background-size: cover:背景图按比例自适应缩放,确保完全填充容器(可能会裁剪图片边缘,但能保证无空白)
  • background-position: center center:强制背景图的中心点与容器中心点对齐,避免重要内容被裁剪
  • 后续的.content容器会自然排列在.hero下方,用户向下滚动时就会逐步显示,和你参考的网站效果完全一致
额外优化建议
  • 如果担心背景图加载慢导致首屏空白,可以给.hero设置一个和背景图主色调接近的background-color作为占位色
  • 针对移动端,可以添加媒体查询调整文字大小,确保小屏幕上的显示效果
  • 如果需要首屏背景图固定(滚动时背景图保持不动),可以给.hero添加background-attachment: fixed,不过这会改变滚动体验,按需选择即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:06:37