Stacking without z-index

« CSS « Understanding CSS z-index

Stacking without z-index

When no element has a z-index, elements are stacked in this order (from bottom to top):

  1. Background and borders of the root element
  2. Descendant blocks in the normal flow, in order of appearance (in HTML)
  3. Descendant positioned elements, in order of appearance (in HTML)

In the following example, absolute and relatively positioned blocks are properly sized and positioned to illustrate the stacking rules.

Notes:

  • Given a homogeneous group of elements without any z-index property, such as the positioned blocks (DIV #1 to #4) in the example, the element's stacking order is their order in the HTML hierarchy, regardless of their position.
  • Standard blocks (DIV #5) in the normal flow, without any positioning property, are always rendered before positioned elements, and appear below them, even if they come later in the HTML hierarchy. 

understanding_zindex_01.png

 

Example

HTML

<div id="absdiv1">
    <br /><span class="bold">DIV #1</span>
    <br />position: absolute; </div>
<div id="reldiv1">
    <br /><span class="bold">DIV #2</span>
    <br />position: relative; </div>
<div id="reldiv2">
    <br /><span class="bold">DIV #3</span>
    <br />position: relative; </div>
<div id="absdiv2">
    <br /><span class="bold">DIV #4</span>
    <br />position: absolute; </div>
<div id="normdiv">
    <br /><span class="bold">DIV #5</span>
    <br />no positioning </div>

CSS

 .bold {
     font-weight: bold;
     font: 12px Arial;
 }
 #normdiv {
     height: 70px;
     border: 1px dashed #999966;
     background-color: #ffffcc;
     margin: 0px 50px 0px 50px;
     text-align: center;
 }
 #reldiv1 {
     opacity: 0.7;
     height: 100px;
     position: relative;
     top: 30px;
     border: 1px dashed #669966;
     background-color: #ccffcc;
     margin: 0px 50px 0px 50px;
     text-align: center;
 }
 #reldiv2 {
     opacity: 0.7;
     height: 100px;
     position: relative;
     top: 15px;
     left: 20px;
     border: 1px dashed #669966;
     background-color: #ccffcc;
     margin: 0px 50px 0px 50px;
     text-align: center;
 }
 #absdiv1 {
     opacity: 0.7;
     position: absolute;
     width: 150px;
     height: 350px;
     top: 10px;
     left: 10px;
     border: 1px dashed #990000;
     background-color: #ffdddd;
     text-align: center;
 }
 #absdiv2 {
     opacity: 0.7;
     position: absolute;
     width: 150px;
     height: 350px;
     top: 10px;
     right: 10px;
     border: 1px dashed #990000;
     background-color: #ffdddd;
     text-align: center;
 }

Result

(If the image does not display in CodePen, click the Tidy button in the CSS section)

See also

 

Original Document Information

 

Document Tags and Contributors

 Last updated by: SphinxKnight,