Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

element with higher z-index value not overlaying another

Tags:

html

css

z-index

I have this code

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

#tsub is appearing on top of #mtitle, and I do not know why.

like image 882
Damon Jenkins Avatar asked Mar 17 '16 23:03

Damon Jenkins


2 Answers

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>
like image 113
dippas Avatar answered Oct 26 '22 03:10

dippas


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

like image 22
Buzilla Avatar answered Oct 26 '22 03:10

Buzilla