Really weird behavior, my content below my header positions itself above my header which I gave a higer z-index. As a consequence it hides the shadow on the header. See snippet. Even stranger behavior when you add a negative margin on the content below: You can see the header text but now has a background color from the content. What the hell?
header {
z-index: 999999;
background-color:green;
width: 100%;
text-align: center;
box-shadow: 0 0ex 2ex hsl(0, 0%, 0%);
vertical-align: middle;
}
div {
background: red;
height: 8em;
/*margin-top: -5em;*/
}
<body >
<header> Some textw<br><br>Some more text</header>
<div>My div</div>
</body>
I tried putting a negative z-index on my content and that solves the problem, but then all elements in my content become inactive. E.g. can't click or hover anything anymore..
CodePudding user response:
The z-index property works only on positioned elements. Those include position: relative
, position: absolute
, position: fixed
, and position: sticky elements
.
Try to give your div #middle
a position: relative
.
header {
position: relative;
z-index: 999999;
background-color:green;
width: 100%;
text-align: center;
box-shadow: 0 0ex 2ex hsl(0, 0%, 0%);
vertical-align: middle;
}
CodePudding user response:
To add to Biswajit answer, here's a good explanation on why position is needed.
CodePudding user response:
When you are working with z-index
, be sure to set positions to the elements. Otherwise it can generate strange behavior.
So here just add position: relative
to the header
and it will work well (even in the case you add that negative margin
to the div
).
In this particular example there is no need to add position: relative
to the div
(in order to solve the issue), but you will not make a mistake doing so. When it comes to play with z-index, setting positions to the overlapping elements help browser to understand the context better.
header {
z-index: 999999;
background-color: green;
width: 100%;
text-align: center;
box-shadow: 0 0ex 2ex hsl(0, 0%, 0%);
vertical-align: middle;
position: relative;
}
div {
position: relative;
background: red;
height: 8em;
margin-top: -5em;
}
Here is btw very good article covering all the z-index issues: https://coder-coder.com/z-index-isnt-working/