element with higher z-index value not overlaying another

Although other answers posted here solve the problem, they are not entirely correct.

The following statements are false:

  • z-index only works on positioned elements.
  • z-index only works on elements that are positioned.
  • z-index only works on elements which are not position:static ie the default position.

In many cases an element must be positioned for z-index to work. But this is not true for all cases.

Elements that are flex items or grid items can create stacking contexts with z-index, even when position is static (see demo).

In terms of this specific question, the reason #tsub is appearing on top of #mtitle is because:

  1. div#tsub comes after h1#mtitle in the HTML, AND
  2. the z-index property applied to #mtitle is being ignored since #mtitle is not positioned, nor is it a flex or grid item.

Here are two possible solutions:

  1. change z-index: 0 on #tsub to z-index: -1, OR
  2. add position: relative to #mtitle

#mtitle {
  display: inline-block;
  margin: 0;
  background-color: aqua;  /* changed for illustration purposes */
  z-index: 999;
}
#tsub {
  display: inline-block;
  margin-left: 0;
  left: 0;
  position: absolute;
  font-size: 85px;
  z-index: -1;   /* adjustment here */
}
<header>
  <h1 id="mtitle">Tepid Beans</h1>
  <div id="tsub"><span>- Games</span>
  </div>
</header>

z-index works on positioned elements, but with CSS3 elements which are flex items or grid items can use z-index when elements are static

From MDN

The z-index property specifies the z-order of an element and its descendants. When elements overlap, z-order determines which one covers the other. An element with a larger z-index generally covers an element with a lower one.

For a positioned box, the z-index property specifies:

  • The stack level of the box in the current stacking context.

  • Whether the box establishes a local stacking context.

Applies to positioned elements

Set position:relative to parent header and position:absolute to #mtitle and change z-index value

body {
  margin: 0
}
header {
  position: relative
}
#mtitle {
  display: inline-block;
  background-color: #000000;
  position: absolute;
  margin:0;
  z-index: 0;
  color: #fff
}
#tsub {
  display: inline-block;
  left: 0;
  position: absolute;
  font-size: 85px;
  z-index: -1;
  background: red
}
<header>
  <h1 id="mtitle">Tepid Beans</h1>
  <div id="tsub">- Games</div>
</header>

z-index only works on elements that are positioned. So if you add position: relative; to #mtitle the z-indexing will work.

Tags:

Html

Css

Z Index