I want the div1
to be above div2
. I try with z-index
but it does not work.
I've tried this code:
div {
width: 100px;
height: 100px;
}
.div1 {
background: red;
z-index: 1;
}
.div2 {
background: blue;
margin-top: -15vh;
z-index: 2
}
<div class="div1"></div>
<div class="div2"></div>
You can add
position: relative
to both divs and createstacking context
Or you could use
transform-style: preserve-3d;
so now.div1
should be positioned in the 3D-space and not flattened in the plane.You can also use some random
transform
liketranslate
orrotate
Filters
also work but they have badSupport
z-index
only applies to elements with aposition
other thanstatic
, so for example:relative
,absolute
, orfixed
.The default property for
div
isposition:static
, Addposition:relative
in both thediv
then onlyz-index
will work.In many cases an element must be positioned for
z-index
to work.Indeed, applying
position: relative
to the divs in the question would solve thez-index
problem.Actually,
position: fixed
,position: absolute
andposition: sticky
will also enablez-index
, but those values also change the layout. Withposition: relative
the layout isn't disturbed.Essentially, as long as the element isn't
position: static
(the default value) it is considered positioned andz-index
will work.Some answers here and in related questions assert that
z-index
works only on positioned elements. As of CSS3, this is no longer true.Elements that are flex items or grid items can use
z-index
even whenposition
isstatic
.From the specs:
Here's a demonstration of
z-index
working on non-positioned flex items: https://jsfiddle.net/m0wddwxs/