Elements in HTML are positioned on the z-axis according to their stacking context.
By default a page has 1 stacking context – the HTML element – and all children of a stacking context are positioned according to their DOM order.
However, a new stacking context can be created on an element when certain CSS properties are applied. Properties such as position: absolute
or position: relative
are commonly used to create new stacking contexts, which is why you are able to position them on the z-axis with z-index
. When a new stacking context is created, it is positioned above the parent stacking context by default.
transform
is another CSS property that will create a new stacking context (since you can transform an element on the z-axis). Since the .blue
element has a transform
but the .red
element doesn't when you comment out the animation, it gets a new stacking context which defaults to above the parent stacking context (which includes the .red
element).
So to get the .blue
box to always stay on top, you'll need to add position: relative
and z-index: 1
to it.
.blue {
position: relative;
z-index: 1;
transform: translate(30%);
}