Skip to content Skip to sidebar Skip to footer

Why Does Text On The Same Layer Overlap - Even When It Has An Opaque Background?

I know that I can stack elements in separate layers by creating new stacking contexts with relative/absolute positioning (Demo) or opacity (Demo) However I was under the impression

Solution 1:

Why does text on the same layer overlap - even when it has an opaque background?

The spec says (emphases mine):

Within each stacking context, the following layers are painted in back-to-front order:

  1. the background and borders of the element forming the stacking context.
  2. the child stacking contexts with negative stack levels (most negative first).
  3. the in-flow, non-inline-level, non-positioned descendants.
  4. the non-positioned floats.
  5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  7. the child stacking contexts with positive stack levels (least positive first).

The backgrounds and the text are considered separately in the painting order: the backgrounds are represented by #3, and the text is represented by #5. The second element appears later in the source, so it is painted over the first, but the text still needs to be painted over the backgrounds, because the two elements are participating in the same stacking context.

Must I create a new stacking context to prevent the text overlapping here?

Yes, the best way to deal with this is by positioning the elements or by having them establish their own stacking contexts. A stacking context is always self-contained, so having each element establish its own stacking context will always ensure that the backgrounds and text of the two elements don't overlap one another.


Solution 2:

If you add position: relative; to the divs it fixes it. At the moment they have the default position: static; which is causing this effect.


Post a Comment for "Why Does Text On The Same Layer Overlap - Even When It Has An Opaque Background?"