Strange css behavior with layers

2019-07-06 18:19发布

Recently i worked at site gallery, and trying to make description label in front of image. So, this is how it should look:

enter image description here

its 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>

Block with .annotation class is absolute, and .project-item is relative. But before that i used another solution which look odd to me, and i cant explain its behavior. Here it is:

enter image description here

I replaced position: absolute rule with margin-top: -50px, and change color from black to red, for clarity.
Strange thing is, that background color displayed back from image, but it should be in front of it, why ? is there any reasonably css rule ?

1条回答
来,给爷笑一个
2楼-- · 2019-07-06 18:55

The reason you are seeing text separated from it's background is because element backgrounds and foregrounds are independent.

I added a black background to the .project-item li and you can see that the red child bg is correctly positioned on top of the black parent bg. .annotation appears in the DOM after the img so those foregrounds are also properly layered. If you want your red annotation background to be visible above the li foreground then you are required to start a new document flow scoped within li.project-item.

In this case the desired positioning is achieved with .slider .project-item .annotation{ position: absolute;} which is currently overridden by your static positioning.

Backgrounds layered properly

查看更多
登录 后发表回答