首页 > 解决方案 > CSS:半透明的半透明文本:伪元素之后

问题描述

刚刚第一次看到不透明与 rgba 的关系,并试图确认两者是否/为什么不能像它看起来那样混合好。

基本示例:

我有一个带有背景图像的全屏 div。该 div 使用带有深色十六进制背景颜色和不透明度的 :after 伪进行深色覆盖。

然后,我使用 z-index 和 rgba 在顶部有一个绝对定位的浅色标题。

当我使用混合的十六进制 BG 和 rgba 标题时,标题看起来像纯灰色 - 好像标题是透明的,但暗 :after 伪元素在标题所在的位置失去了透明度。

通过将标题更改为十六进制和不透明度,而不是 rgba,一切都是透明的,完全符合设计的要求。

谁能解释为什么将两者混合会造成麻烦?我很难找到正确的 Google/Stack 搜索来获得明确的答案。

HTML 的精简版

<section id="banner">
  <div class="inner">
    Some content
  </div>
  <h2 class="transparent">The heading in question</h2>
</section>

删节的 CSS:

#banner {
  position:absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background-image: url('pathto/image.jpg');
  background-size: cover;  
}

#banner:after {
  content: '';
  display: block;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: #000;
  opacity: 0.35;
}

#banner .inner {
  z-index: 2;
}

.transparent {
  z-index: 2;
  position: absolute;
  bottom: 0;
  right: 0;
  color: rgba(255,255,255,.5);
}

标签: htmlcss

解决方案


试试这个方法...

#banner {
  position:absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Pigeon_Point_Lighthouse_%282016%29.jpg/220px-Pigeon_Point_Lighthouse_%282016%29.jpg');
  background-size: cover;  
}

#banner:after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: rgba(0,0,0,0.55);
}

#banner .inner {
  z-index: 2;
}

.transparent {
  z-index: 2;
  position: absolute;
  bottom: 0;
  right: 0;
  font-size: 53px;
  color: rgba(255,255,255,.25);
}
<section id="banner">
  <div class="inner">
    Some content
  </div>
  <h2 class="transparent">The heading in question</h2>
</section>


推荐阅读