DEV Community

Cover image for Quick CSS Quiz #5

Quick CSS Quiz #5

Abdelrahman Ismail on October 21, 2018

In this series, I try to focus on CSS weird parts, throw quiz and its answer, hoping to give a better understanding of how CSS works in depth. ...
Collapse
 
ismail9k profile image
Abdelrahman Ismail • Edited

This quiz requires a deep knowledge of how CSS z-index works, we will start by applying the first four CSS rule-sets:

.red { z-index: 100; }
.blue { z-index: 50; }
.green { z-index: 2; }
.black { z-index: 0; }

This will re-arrange the squares as flowing: .black in the most back then .green then .blue and finally the '.red' at the top, this arrange is intuitive, an element with a larger z-index covers an element with a lower one.
But when you add the final rule-set

.first { transform: translateZ(10px); }

You expect to move the .first two square (red and green squares) to be on top of the other squares (black and blue squares), but you got a completely different output, and the z-index now is completely unreasonable.

CSS has layers which is slightly looks like the Photoshop layers (surprise), z-index arrange elements within that layer, larger z-index element on top and the smaller on bottom, that's what happened when you added transform property you make .first a separate layer with auto z-index, so it will behind the .second div elements.

And this is how it will looks in Chrome DevTool Layers Panel

Squares

Collapse
 
stephanie profile image
Stephanie Handsteiner

That's a good one, I almost fell for the seemingly logical solution without giving it a proper thought, but in the end I got it. 😁

green and red are children of first, red has, with a 100, the higher index than green with its 2 and therefore is on top of green.
black and blue are children of second, blue with 50 has the higher index than black with 0 and therefore is in the front.

Collapse
 
somedood profile image
Basti Ortiz

Oh, that is very clever. I should've read the HTML first before I made my answer.

Collapse
 
ismail9k profile image
Abdelrahman Ismail

What was your answer? and can you guess why they are arranged in this way? 😄

Collapse
 
somedood profile image
Basti Ortiz

Well, at first, I chose the intuitive answer. I'm sure you know what I mean by that. Then when I scrolled down to see the actual answer, it took me a while to realize that the HTML structure played a huge part in the z-indices of the divs. I should really look more carefully next time. Looking forward to more of your puzzles!