CSS动画如何更改Z-index? [英] How come css animations change z-index?

查看:51
本文介绍了CSS动画如何更改Z-index?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么动画会更改z-index?

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

如果您查看jsfiddle,您会看到红色图像位于顶部,但是如果您注释掉动画,则蓝色图像位于顶部.即使使用动画,如何使蓝色图像始终位于最上方?

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);
  }
}

非常感谢您的帮助!

推荐答案

HTML中的元素根据其

Elements in HTML are positioned on the z-axis according to their stacking context.

默认情况下,页面具有1个堆叠上下文(HTML元素),并且堆叠上下文的所有子级均根据其DOM顺序放置.

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.

但是,当应用某些CSS属性时,可以在元素上创建新的堆叠上下文.通常使用诸如 position:absolute position:relative 之类的属性来创建新的堆叠上下文,这就是为什么您可以使用将它们放置在z轴上的原因> z-index .创建新的堆栈上下文后,默认情况下它将位于父堆栈上下文上方.

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 是另一个CSS属性,它将创建新的堆叠上下文(因为您可以在z轴上转换元素).由于 .blue 元素具有 transform ,但是 .red 元素在注释掉动画时没有,因此它获得了一个新的堆叠上下文默认为父级堆叠上下文(包含 .red 元素)之上.

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).

因此,要使 .blue 框始终位于顶部,您需要添加 position:relative z-index:1 .

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%);
}

这篇关于CSS动画如何更改Z-index?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆