Friday, November 10, 2017

CSS overlapping and z-index

In CSS, there are three different things that impact how html elements overlap each other: stacking contexts, source order, and painting order (a.k.a. stacking level).

Stacking contexts
When you apply z-index to a positioned element, you do two things.

First, you say that the element is in front or behind other elements that share the same stacking context. This is what we normally think about when we change z-index -- we want something to move in front or in back of something else.

Second, you create a new stacking context for anything inside the positioned element. Once you've created a stacking context, any layering that happens inside that stacking context stays in that context. This is the part we forget.

In a normal document, without any positioning, the document has exactly one stacking context -- the one created by html. When dealing with positioning, the stacking context is probably the hardest thing to remember.

Source code
There are two different ways of looking at an HTML document source code. One is by reading, from top to bottom, to see which tags start before which tags. The other way to look at this is in tree order where you keep track of not only which tags start first, but also which tags are inside other tags.

Stacking levels (inside of stacking contexts)
Normally, adjusting the z-index property and keeping track of stacking contexts is all you need to worry about. But occasionally you'll run into a situation where one box paints over another, even though there's no positioning involved. This happens because of how data is stacked inside of a stacking context. Just to make things confusing, the specs call this concept stacking levels.

The specs define 7 painting layers. Starting from back to front, they are:
  1.     The borders and background of the current stacking context
  2.     Positioned descendants with negative z-index (or goes before #1 in modern browsers)
  3.     Non-positioned block-level descendants with no z-index property defined -- paragraphs, tables, lists, and so on
  4.     Floating descendants and their contents
  5.     Non-positioned inline content
  6.     Positioned descendants with no z-index, z-index: auto, or z-index: 0
  7.     Positioned descendants with z-index greater than 0

Some key points to remember:
  1. Source order counts.
  2. Inline elements paint over floats.
  3. Positioned elements paint on top of everything else if they don't have negative z-index.
http://css-discuss.incutio.com/wiki/Overlapping_And_ZIndex
The reference article has details including examples to explain CSS overlapping within stacking contexts.


No comments:

Post a Comment