Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

html - Why using absolute position causes the div to be on top?

Please see this very simple snippet to illustrate my question below:

#container {
  position: relative;
  padding: 20px;
  border: 2px solid gray;
}

#back {
  position: absolute;
  top: 0;
  bottom: 50%;
  left: 0;
  right: 0;
  background-color: #bbb;
}
<div class="col-sm-12" id="container">
  <div id="back"></div>
  <h1>Some Text</h1>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is how the painting order works. As described here you have the following order:

  1. For all its in-flow, non-positioned, block-level descendants in tree order: If the element is a block, list-item, or other block equivalent:

In this step you will print the background and border of the h1 element

  1. Otherwise: first for the element, then for all its in-flow, non-positioned, block-level descendants in tree order:

In this complex step you will print the content of the h1 element

  1. All positioned, opacity or transform descendants, in tree order that fall into the following categories:

    1. All positioned descendants with 'z-index: auto'

And in this step you will print the positioned element #back; thus it will be on the top of h1 even if in the DOM it's before.

In other words, we first consider the in-flow elements then the postioned ones. Of course, changing z-index and/or other properties will affect the order because more steps can be consider.


For example adding a negative z-index to #back will trigger this rule:

  1. Stacking contexts formed by positioned descendants with negative z-indices (excluding 0) in z-index order (most negative first) then tree order.

This will make the #back to be behind since h1 is printed later in the step (4) and (7).


Adding position:relative (or absolute or fixed) to h1 will make it a positioned element so like #back it will trigger the (8) and in this case the tree order will decide.


You may also notice that both background and content are printed in 2 different steps and this may also lead to some non intuitive painting behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...