Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come css animations change z-index? [duplicate]

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!

like image 516
Jeff Avatar asked Oct 24 '25 18:10

Jeff


1 Answers

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%);
}
like image 161
Steven Lambert Avatar answered Oct 26 '25 07:10

Steven Lambert