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

如何为多个HTML Sections设置连续背景渐变(无法用容器包裹)

实现多个独立section的连续渐变背景

我有多个独立的<section>元素,每个都带有背景渐变样式,但受限于构建机制,没法把这些section都包裹在一个容器里。当前每个section都会单独显示完整的渐变效果,我需要让所有section共用一个连续的渐变——从第一个section顶部开始,到最后一个section底部结束。

当前代码:

.grad-back{
background: rgb(0,92,109);
background: linear-gradient(180deg, rgba(0,92,109,1) 0%, rgba(1,12,14,1) 39%, rgba(1,9,10,1) 65%, rgba(0,93,110,1) 100%);
}
section {
height:200px;
}
<section class="grad-back">one</section>
<section class="grad-back">two</section>
<section class="grad-back">three</section>

方法1:用body作为渐变容器(最简单)

把渐变背景直接设置在<body>上,同时让section背景透明,这样body的渐变会贯穿所有section,自然形成连续效果:

body {
  margin: 0; /* 清除默认边距,避免渐变出现间隙 */
  background: rgb(0,92,109);
  background: linear-gradient(180deg, rgba(0,92,109,1) 0%, rgba(1,12,14,1) 39%, rgba(1,9,10,1) 65%, rgba(0,93,110,1) 100%);
}
section {
  height: 200px;
  background: transparent; /* 透出body的渐变 */
}
<section>one</section>
<section>two</section>
<section>three</section>

方法2:精准控制每个section的渐变片段

如果必须保留section的.grad-back类(比如有其他样式依赖),可以通过background-size和background-position让每个section只显示完整渐变的对应段落:

.grad-back{
  background: rgb(0,92,109);
  background: linear-gradient(180deg, rgba(0,92,109,1) 0%, rgba(1,12,14,1) 39%, rgba(1,9,10,1) 65%, rgba(0,93,110,1) 100%);
  background-size: 100% 600px; /* 渐变高度设为3个section的总高度(200*3) */
}
/* 第一个section显示渐变的前200px */
section:nth-child(1) {
  background-position: 0 0;
}
/* 第二个section显示渐变的中间200px */
section:nth-child(2) {
  background-position: 0 200px;
}
/* 第三个section显示渐变的最后200px */
section:nth-child(3) {
  background-position: 0 400px;
}
section {
  height: 200px;
  margin: 0; /* 清除默认边距避免间隙 */
}
<section class="grad-back">one</section>
<section class="grad-back">two</section>
<section class="grad-back">three</section>

方法3:CSS变量动态适配(适合高度不固定的场景)

如果section高度不固定,用CSS变量结合calc()可以动态计算每个section的背景位置:

:root {
  --section-height: 200px; /* 单个section的高度 */
  --total-sections: 3; /* section的数量 */
  --total-height: calc(var(--section-height) * var(--total-sections));
}
.grad-back{
  background: rgb(0,92,109);
  background: linear-gradient(180deg, rgba(0,92,109,1) 0%, rgba(1,12,14,1) 39%, rgba(1,9,10,1) 65%, rgba(0,93,110,1) 100%);
  background-size: 100% var(--total-height);
}
section:nth-child(1) {
  background-position: 0 0;
}
section:nth-child(2) {
  background-position: 0 calc(var(--section-height) * 1);
}
section:nth-child(3) {
  background-position: 0 calc(var(--section-height) * 2);
}
section {
  height: var(--section-height);
  margin: 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:04:58