3

Why is it that the animation changes the z-index?

If you look at the jsfiddle, you'll see the red image is on top but if you comment out the animation, the blue image is on top. How can I get the blue image to always be on top even with the animation?

jsfiddle

HTML

<img class="blue" src="http://via.placeholder.com/200/0037ff">
<img class="red" src="http://via.placeholder.com/200/ff0010">

CSS

.red {
  -webkit-animation-name: red;
  -webkit-animation-duration: 2s;
  -webkit-animation-iteration-count: infinite;
  animation-name: red;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

.blue {
  transform: translate(30%);
}

@keyframes red {
  from {
    transform: translate(50%);
  }
  to {
    transform: translate(0);
  }
}

Any help is much appreciated!

Jeff
  • 129
  • 1
  • 2
  • 13

3 Answers3

5

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%);
}
Steven Lambert
  • 5,571
  • 2
  • 29
  • 46
0

CSS Animations reset the z-index.

So what you probably have to do is give the red image a z-index of 0 and the blue image a z-index of 1.

Advena
  • 1,664
  • 2
  • 24
  • 45
0

Why dont you put a z-index value on .blu?

try this:

.blue{
z-index: 999;
transform: translate(30%);
}
Jaziel_Inc
  • 82
  • 2
  • 9