0

Given my code below:

img
{
  width:400px;
}

div {
  border:2px solid blue;
  width:200px;
  height:100px;
  margin-top:-70px;
  z-index:999999999;
}
<img src="https://i.gyazo.com/ee6bb88b3da7ce038475b8ce27fb5fbb.jpg" />

<div>
</div>

Logically speaking, the <div> is created after the <img>, so <div> should overlap the <img> element when I give it a negative margin. But why is the <img> element covering the <div> instead, and even with z-index applied to the <div>, it doesn't work?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Xeon
  • 385
  • 3
  • 11

1 Answers1

4

The CSS property z-index only works in the element whose position property has been set to a different value other than the default value.

So in a default element <div>, the position property is by default set to static. So in order to control the vertical stacking (z-index) relative to other components you first need to set the position, e.g. position: relative;.

You can read more here

Here's your example:

img
{
  width:400px;
}

div {
  border:2px solid blue;
  width:200px;
  height:100px;
  margin-top:-70px;
  z-index:999999999;
  position: relative;
}
<img src="https://i.gyazo.com/ee6bb88b3da7ce038475b8ce27fb5fbb.jpg" />
<div>
</div>
Arman Ebrahimi
  • 2,035
  • 2
  • 7
  • 20
Mosia Thabo
  • 4,009
  • 1
  • 14
  • 24