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:
div#tsub comes after h1#mtitle in the HTML, AND
- 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:
- change
z-index: 0 on #tsub to z-index: -1, OR
- 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>