2

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?

Jonathan
  • 1,542
  • 3
  • 16
  • 24
CyanPrime
  • 5,096
  • 12
  • 58
  • 79
  • 2
    (hope it's just for demo purposes but) You should avoid using inline styles... It's terribly hard to work-with and maintain. – Roko C. Buljan Oct 05 '14 at 19:56

2 Answers2

4

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.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
1

Add position:relative; in css of both blocks:

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

http://jsfiddle.net/uu721kgc/

MaximOrlovsky
  • 265
  • 2
  • 8