在绝对定位的 div 上方放置相对定位的内容

4
我正在尝试将文本放置在图像上(这里简化为一个div),我可以对其进行模糊处理和设置其他过滤器,但我希望该文本是相对定位的,以便父容器可以调整大小。

#container {
  position: relative;
  width: 100%;
  background: red;
  height: 300px; /* For display sample purposes--no height is defined in production */
}

.bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: blue;
  opacity: 0.5;
}

.content {
  color: white;
  font-weight: bold;
  font-size: 3em;
}
<div id="container">
  <div class="bg"></div>
  <div class="content">
    asdasdasdasd
  </div>
</div>

这会导致蓝色的 bg 显示在 content 上方。我知道可以将 content div 也绝对定位,但那样容器的高度不会改变。

我该如何实现我想要的效果呢?

Fiddle


你的问题是什么?在这个例子中,“content”已经在“bg”的顶部。 - Abin Thaha
@Abinthaha 不是这样的。我把文本变成了白色和更大,以使问题更清晰 - bg 显然在文本上方,使其呈蓝色。如果你提高 bg 的不透明度,文本将完全不可见。 - idlackage
2个回答

2
将以下样式添加到 .content 类中。
.content {
  position: relative;
 z-index: 1;
}

现在我感到有些尴尬,竟然要问这个问题...真的,为什么我没想到呢?谢谢。 - idlackage

0

我认为这个东西对你有用,希望它能对你有所帮助。试试看吧。

#main {
  position: relative;
  height: 200px;
  width: 200px;
  border: 2px solid #aaa;
  text-align:center
}
#center {
  position: relative;
  left:25%;
  top:25%;
  border: 1px solid #aaa;
  width: 100px;height: 100px; 
  text-align:center
}

div { height: 50px;width: 50px;}

.blue { background-color: lightblue; position: absolute; }
.green {background-color: lightgreen; position: absolute; right:0}
.yellow {background-color: yellow; position: absolute; right:0; bottom:0 }
.red {background-color: lightpink; position: absolute;  bottom:0;}
<div id="main">
  <div class="blue">blue</div>
  <div class="green">green</div>
  <div class="yellow">yellow</div>
  <div class="red">red</div>
  <div id="center">
    <div class="blue">center-blue</div>
    <div class="green">center-green</div>
    <div class="yellow">center-yellow</div>
    <div class="red">center-red</div>
  </div>
</div>
<p>This is relative absolute using css.</p>


1
我对你能够从那个问题中推理出这个答案感到印象深刻。 - ippi
我很高兴能够帮助您并给出积极的回应。 - Rudra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接