最近我在网站库工作,并试图在图像前面制作描述标签。所以,这应该是它的样子:
它的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是相对的。 但在此之前,我使用了另一种对我来说很奇怪的解决方案,我无法解释它的行为。这是:
我将position: absolute
规则替换为margin-top: -50px
,并将color
从黑色更改为红色,为清晰起见。
奇怪的是,背景颜色从图像显示回来,但它应该在它的前面,为什么呢?有没有合理的css规则?
答案 0 :(得分:1)
您看到文本与其背景分离的原因是因为元素背景和前景是独立的。
我在.project-item
li
添加了黑色背景,您可以看到红色子bg正确定位在黑色父bg的顶部。在.annotation
之后,img
出现在DOM中,因此这些前景也正确分层。如果您希望红色注释背景在li
前景上方可见,则需要在li.project-item
范围内启动新的文档流。
在这种情况下,.slider .project-item .annotation{ position: absolute;}
实现了所需的定位,目前static
定位会覆盖{。}}。