z-index not indexing properly

This question already has an answer here:

Alright, so this code generates two blocks in a div. The top block should go over the bottom block because the top has a higher z-index, but when I give the bottom block a margin-top: -30px it goes above the top block.

<html>
<head></head>
<body>
<div style="width: 300px; height: 90px; overflow: hidden;">
  <div style="width:300px; height: 50px; z-index: 2; background-color: #ff0000;">
  </div>
  <div style="width:300px; height: 50px; z-index: 1; background-color: #ff00ff; margin-top: -30px;">
  </div>
</div>
</body>
</html>

How do I get the top block to go above the bottom block?


solution

The z-index property only applies to positioned elements.

You could add position: relative and it will work as expected (example).

The default value of the position property is static, which is why it wasn’t working.