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

如何设置黑色元素透明以显示后方背景(含渐变/图片场景)

实现透明条穿透容器渐变显示后方背景

注意:HTML中多个元素使用同一个id不符合规范(id必须唯一),首先需要将所有id="myBar"改为class="myBar"。

完整代码实现

CSS

/* 示例:设置后方背景(比如body的背景),可以是图片或纯色 */
body {
  background: url('your-background-image.jpg') center/cover no-repeat;
  /* 或者纯色替代:background: #e0e0e0; */
}

#myElement {
  width: 50px;
  height: 300px;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
}

/* 用伪元素实现容器的渐变背景,放在内容下方 */
#myElement::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(0deg, #4a94cd, #fe49a6);
  z-index: 0;
}

.myBar {
  width: 100%;
  height: 10px;
  background: transparent; /* 透明状态,穿透显示后方背景 */
  position: relative;
  z-index: 1; /* 确保条块在渐变背景之上 */
}

HTML

<div id="myElement">
  <div class="myBar"></div>
  <div class="myBar"></div>
  <div class="myBar"></div>
  <div class="myBar"></div>
  <div class="myBar"></div>
  <div class="myBar"></div>
  <div class="myBar"></div>
  <div class="myBar"></div>
  <div class="myBar"></div>
  <div class="myBar"></div>
</div>

原理说明

  • 先修正HTML的ID问题:同一个页面里id是唯一标识,不能重复使用,所以改成class。
  • 分离渐变背景和内容层:容器本身不设置背景,用伪元素生成渐变并放在内容下方,这样内容层可以独立控制显示效果。
  • 透明条块穿透显示:把.myBar设为透明,同时让它在渐变背景的上层,这样这些条块就能直接透出容器后方的背景(不管是图片还是纯色),容器其他区域正常显示渐变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 15:51:53