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

如何让滚动容器的背景阴影显示在带背景色的子元素上方?

问题:滚动容器顶部阴影被禁用项背景覆盖,如何让阴影显示在上方?

我有一个包含子元素的可滚动容器:

<ul class="scroll-shadows">
  <li>Adipisci, totam.</li>
  <li>Error, dicta.</li>
  <li class="disabled-item">Disabled input</li>
  <li>Eveniet, dolorem!</li>
  ...
</ul>

为这个容器设置了顶部渐变阴影背景:

background:
  linear-gradient(
    gray, white
  ) center top;
background-repeat: no-repeat;
background-size: 100% 60px;
background-attachment: scroll;

其中禁用状态的子元素拥有独立背景色:

.disabled-item {
  background-color: #F6F6F7;
}

问题在于禁用元素的背景色会覆盖容器的顶部阴影,尝试过background-blend-mode和z-index都没有效果,请问如何让阴影优先显示在上方?


解决方案

核心问题是容器的背景绘制在子元素下方,所以子元素的背景会遮挡它。要让阴影显示在子元素上方,最直接的方法是用容器的伪元素来实现阴影,而非容器自身的背景。

具体实现步骤:

  1. 给容器添加position: relative,让伪元素可以相对于容器定位;
  2. 移除容器原有的background相关样式;
  3. 添加伪元素::before,设置绝对定位在容器顶部,使用渐变阴影,并通过pointer-events: none确保不阻挡子元素的交互。

修改后的CSS代码:

.disabled-item {
  background-color: #F6F6F7;
}

.scroll-shadows {
  width: 600px;
  max-height: 300px;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  overflow-scrolling: touch;
  position: relative; /* 添加相对定位 */
  /* 移除原有的background相关样式 */
}

/* 添加伪元素实现顶部阴影 */
.scroll-shadows::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 60px; /* 和原阴影高度一致 */
  background: linear-gradient(gray, white);
  pointer-events: none; /* 允许点击穿透到子元素 */
  z-index: 1; /* 确保阴影在子元素上方 */
}

/* 原有演示样式保留 */
.scroll-shadows {
  list-style: none;
  padding-left: 1rem;
  padding-right: 1rem;
}
.scroll-shadows > * {
  padding: 0.2rem;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  height: 100vh;
  display: grid;
  place-items: center;
  font: 500 100% system-ui, sans-serif;
}
.scroll-shadows {
  --scrollbarBG: transparent;
  --thumbBG: #90a4ae;

  scrollbar-width: thin;
  scrollbar-color: var(--thumbBG) var(--scrollbarBG);
}
.scroll-shadows::-webkit-scrollbar {
  width: 8px;
}
.scroll-shadows::-webkit-scrollbar-track {
  background: var(--scrollbarBG);
}
.scroll-shadows::-webkit-scrollbar-thumb {
  background-color: var(--thumbBG);
  border-radius: 6px;
  border: 3px solid var(--scrollbarBG);
}

原理说明:

  • 伪元素::before是容器的子元素,但通过position: absolute和z-index:1可以浮在所有默认定位(static)的子元素上方;
  • pointer-events: none保证阴影不会拦截鼠标点击、滚动等交互操作,完全不影响子元素的可用性;
  • 这种方式避免了容器背景和子元素背景的层级冲突,完美解决阴影被遮挡的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 23:46:31