我是否遇到了导致渲染错误的边缘情况,或者我是否编写了一些糟糕的 CSS?
为了复制这一点,我编写了以下演示:
body
元素嵌套了一个 square
div,它有一个包含一些文本的 span
子元素。
<div class="square">
<span>hello</span>
</div>
body
元素控制 perspective
属性,以便 translateZ
可以工作,但由于某种原因,该道具仅在悬停动画播放完毕后才会触发。
* {
transform-style: preserve-3d;
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 500px;
outline: 1px solid red;
perspective: 1000px;
}
.square {
position: absolute;
display: flex;
justify-content: center;
align-items: center;
height: 100px;
width: 100px;
background-color: blue;
bottom: 0;
opacity: 0;
transition: 500ms;
}
body:hover .square {
bottom: 300px;
opacity: 1;
}
.square span {
color: white;
font-size: 24px;
font-family: sans-serif;
transform: translateZ(45px);
}
到目前为止,我已经在 Edge、Chrome 和 Firefox 中测试了这个示例,并且都得到了相同的结果,所以我真的很想知道我在这里做错了什么。这是 codepen 的链接。
为了进一步理解这个问题,我还附上了一张 gif 来进一步展示这个问题。
注意在 Z 轴上翻译的
span
文本如何在过渡结束后跳转到其属性 transform: translateZ(45px)
。通过更改 span
平移的像素值,可以更好地注意到这种效果。
我真的很想知道发生了什么事以及如何防止这种情况发生。
添加
.square { perspective: 1000px; }
- 这将解决问题。transform
代替 bottom
制作动画,并添加 .square { will-change: transform, opacity; }
。
* {
/* bad idea to set it to all... */
transform-style: preserve-3d;
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 500px;
outline: 1px solid red;
}
.square {
position: absolute;
display: flex;
justify-content: center;
align-items: center;
height: 100px;
width: 100px;
background-color: blue;
transform: translateY(300px);
opacity: 0;
transition: transform .5s, opacity .5s;
perspective: 1000px;
will-change: transform, opacity;
}
body:hover .square {
transform: translateY(0);
opacity: 1;
}
.square span {
color: white;
font-size: 24px;
font-family: sans-serif;
transform: translateZ(400px);
}
<div class="square">
<span>hello</span>
</div>