【问题标题】:see text though the overlay div element通过覆盖 div 元素查看文本
【发布时间】:2022-02-20 11:36:40
【问题描述】:

我有 2 个 div 元素,它们的背景色设置覆盖在另一个 div 的顶部,其中包含内容。在 case-1 覆盖不是内容 div 的兄弟,因此它允许背景文本对用户可见。 在 case-2 中,叠加层是内容 div 的兄弟,因此它不会向用户显示文本。

案例一

<div class="overlay"></div>
<div class="example-container">
  <div class="child1">
    Case 1 - Sample Text 1
  </div>
</div>

案例 2

<div class="child1">
  Case 2 - Sample text 2
</div>
 <div class="overlay">
 </div>

Sample JSfiddle to simulate 2 scenarios.

知道为什么在 html 中有这种行为吗?我们如何才能使具有背景颜色的覆盖 div(案例 2)始终允许文本透明。

【问题讨论】:

标签: html css


【解决方案1】:

这里的问题是 div 是在文本上呈现的。这可以通过为叠加层提供 -1 的 z-index 属性来轻松解决。这使得 div 呈现在文本下方,让您可以看到它。

示例叠加 css

.overlay {
    position: absolute; 
    background-color: gray;
    top:0;
    left:0;
    width: 100px;
    height: 100px;
    z-index: -1;
  }

或者,因为您希望它覆盖(如果您实际上不这样做,那是一个非常容易误导的名称)只需将不透明度设置为较低

.overlay {
    position: absolute; 
    background-color: gray;
    top:0;
    left:0;
    width: 100px;
    height: 100px;
    opacity: 0.5;
  }
 

【讨论】:

  • 感谢大转储。这解决了问题。
【解决方案2】:

为所有同级设置position 属性可以实现此目的。

我发现这篇文章很有帮助,它解释了各种场景。 https://coder-coder.com/z-index-isnt-working/

一个有效的示例小提琴。 https://jsfiddle.net/praveenr/ukpw63hc/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    相关资源
    最近更新 更多