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

实现#View外可见的滚动#Content,添加深色遮罩并保持边框层级

问题与解决方案

现有代码

CSS

body {
  margin: 0;
}

#main {
  width: 100vw;
  height: 100vh;
  background-color: LightCyan;
}

#container {
  display: flex;
  justify-content: center;
  box-sizing: border-box;
  padding-top: 20px;
  padding-bottom: 20px;
  background-color: beige;
}

#view {
  width: 400px;
  height: 200px;
  box-sizing: border-box;
  overflow: scroll;
  border: dotted black 2px;
}

#content {
  width: 320px;
  height: 350px;
  box-sizing: border-box;
  background-color: olive;
}

HTML

<div id='main'>
  <div id='container'>
    <div id='view'>
      <div id='content'></div>
    </div>
  </div>
</div>

需求

  • #Content超出#View的高度部分需可见
  • 超出区域添加深色半透明遮罩,#View内显示的#Content保持原有颜色
  • #View的边框需显示在#Content上方

解决方案

通过调整DOM结构和CSS定位、遮罩属性实现需求,修改后的代码如下:

修改后的HTML

<div id='main'>
  <div id='container'>
    <div class="viewport-wrapper">
      <div id='view'></div>
      <div id='content'></div>
      <div class="mask"></div>
    </div>
  </div>
</div>

修改后的CSS

body {
  margin: 0;
}

#main {
  width: 100vw;
  height: 100vh;
  background-color: LightCyan;
}

#container {
  display: flex;
  justify-content: center;
  box-sizing: border-box;
  padding-top: 20px;
  padding-bottom: 20px;
  background-color: beige;
}

.viewport-wrapper {
  position: relative;
  width: 400px;
  height: 200px;
}

#view {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;
  border: dotted black 2px;
  z-index: 2;
  background-color: inherit;
}

#content {
  width: 320px;
  height: 350px;
  box-sizing: border-box;
  background-color: olive;
  position: absolute;
  left: 50%;
  top: 0;
  transform: translateX(-50%);
  overflow: auto;
  z-index: 1;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  -webkit-mask: linear-gradient(white, white) content-box, linear-gradient(white, white);
  mask: linear-gradient(white, white) content-box, linear-gradient(white, white);
  -webkit-mask-composite: xor;
  mask-composite: exclude;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1;
  pointer-events: none;
}

实现说明

  1. 超出部分可见:将#Content从#View内部移出,通过绝对定位在.viewport-wrapper容器内,脱离#View的overflow限制,超出部分自然展示。
  2. 深色遮罩:利用CSS mask属性实现遮罩层仅显示#View外部区域,对#Content超出部分添加半透明深色覆盖,#View内的内容不受遮罩影响。
  3. 边框层级:给#View设置更高的z-index,确保边框始终显示在#Content和遮罩层上方,同时#View设置背景色继承父容器,避免遮罩透过#View显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 15:55:20