奇怪的css行为与图层

时间:2013-02-24 13:54:30

标签: html css image background

最近我在网站库工作,并试图在图像前面制作描述标签。所以,这应该是它的样子:

enter image description here

它的HTML:

<li class="project-item">
  <img src="images/project_example.jpg" alt="">
  <div class="annotation">
    <div class="annotation_head">Head</div>
    <div class="annotation_footer">Footer</div>
  </div>
</li>

使用.annotation类的块是绝对的,而.project-item是相对的。 但在此之前,我使用了另一种对我来说很奇怪的解决方案,我无法解释它的行为。这是:

enter image description here

我将position: absolute规则替换为margin-top: -50px,并将color从黑色更改为红色,为清晰起见。
奇怪的是,背景颜色从图像显示回来,但它应该在它的前面,为什么呢?有没有合理的css规则?

1 个答案:

答案 0 :(得分:1)

您看到文本与其背景分离的原因是因为元素背景和前景是独立的。

我在.project-item li添加了黑色背景,您可以看到红色子bg正确定位在黑色父bg的顶部。在.annotation之后,img出现在DOM中,因此这些前景也正确分层。如果您希望红色注释背景在li前景上方可见,则需要在li.project-item范围内启动新的文档流。

在这种情况下,.slider .project-item .annotation{ position: absolute;}实现了所需的定位,目前static定位会覆盖{。}}。

Backgrounds layered properly