0

I was building a modal, and I was having problems keeping the background behind the main content. They were on the correct hierarchy for them being painted correctly: the ones behind comes first. The problem was that the absolute position background was "hidding" the content, despite the content should be painted after and therefore in front.

Suddenly I realised that adding position relative to the content make it render on top of the background, so the background-color of the background was not "masking" it anymore.

Here is a fiddle where you can see how the content with the position absolute has the correct colors, while the one with normal position has it's colors tinted red.

.main {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

.background {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(100, 0, 0, 0.55);
}

.content {
  background-color: lightblue;
  padding: 1rem;
  position: relative;
}

.norelative {
  background-color: lightblue;
  padding: 1rem
}
<div>
Just some basic text
</div>
<div class="main">
  <div class="background"></div>
  <div class="content">Content</div>
  <div class="norelative">No relative</div>
</div>

https://jsfiddle.net/danielo515/x3u2Lth7/11/

How is this possible? How can position relative affect this layering problem?

Danielo515
  • 5,996
  • 4
  • 32
  • 66

1 Answers1

1

It's all about stacking contexts. Using a position property that isn't static (the default) makes the element render on top of anything else that is static. So, your background renders on top of the static norelative div, but since the relative div isn't static, it follows the normal rendering order and renders on top of the background.

See stacking context for more details.

bowlowl
  • 417
  • 2
  • 7