Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using z-index to get div above another div

Tags:

html

css

z-index

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>
like image 598
Corentin Branquet Avatar asked Mar 03 '16 12:03

Corentin Branquet


1 Answers

You can add position: relative to both divs and create stacking context

div {
  width:100px;
  height: 100px;
}

.div1 {
  background: red;
  z-index: 2;
  position: relative;
}

.div2 {
  background: blue;
  margin-top: -15vh;
  z-index: 1;
  position: relative;
}
<div class="div1"></div>
<div class="div2"></div>

Or you could use transform-style: preserve-3d; so now .div1 should be positioned in the 3D-space and not flattened in the plane.

div {
  width:100px;
  height: 100px;
}

.div1 {
  background: red;
  z-index: 2;
  transform-style: preserve-3d;
}

.div2 {
  background: blue;
  margin-top: -15vh;
  z-index: 1;
}
<div class="div1"></div>
<div class="div2"></div>

You can also use some random transform like translate or rotate

div {
  width:100px;
  height: 100px;
}

.div1 {
  background: red;
  z-index: 2;
  transform: translate(1px);
}

.div2 {
  background: blue;
  transform: translate(1px, -15vh);
  z-index: 1;
}
<div class="div1"></div>
<div class="div2"></div>

Filters also work but they have bad Support

div {
  width:100px;
  height: 100px;
}

.div1 {
  background: red;
  filter: brightness(0.4);
  z-index: 2;
}

.div2 {
  background: blue;
  margin-top: -15vh;
  filter: brightness(0.4);
  z-index: 1;
}
<div class="div1"></div>
<div class="div2"></div>
like image 174
Nenad Vracar Avatar answered Sep 20 '22 17:09

Nenad Vracar