I was trying to create a stack of overlapping cards (divs with borders) using relative positioning and z-index. However, instead of overlapping, the cards ended up looking like this:

First card

Second card

<div style="border: 1px solid black; width: 200px; height: 200px; position: relative; top: 20px; left: 20px; z-index: 2;">
    First card
</div>
<div style="border: 1px solid black; width: 200px; height: 200px; position: relative; top: -150px; left: 50px; z-index: 1;">
    Second card
</div>

I was flummoxed! Stymied! Flabbergasted! A-bunch-of-other-words-that-sound-impressive-but-mean-the-same-thing! Turns out divs need some sort of background in order for z-index to achieve the effect I was going for. The divs currently DO stack correctly, it’s just impossible to tell that visually. For example, setting the background-color for both divs to white gave me:

First card

Second card

<div style="border: 1px solid black; width: 200px; height: 200px; position: relative; top: 20px; left: 20px; z-index: 2; background-color: white;">
    First card
</div>
<div style="border: 1px solid black; width: 200px; height: 200px; position: relative; top: -150px; left: 50px; z-index: 1; background-color: white;">
    Second card
</div>

I wish CSS were less arcane.

Tagged: