如果在属性末尾设置透视,CSS 3d 变换将不起作用

god*_*rry 5 css css-transforms

我发现transform财产取决于perspective()职位

为什么会发生这种情况?还有其他规则/限制吗transform

虽然我觉得很奇怪,但这似乎不是一个错误,因为我可以在 Chrome/FF 中重现它

box:nth-child(1):hover {
  transform: perspective(1000px) translate3d(0, 0, -100px);
}

box:nth-child(2):hover {
  transform: translate3d(0, 0, 100px) perspective(1000px);
}

box {
  padding: 20px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-family: monospace;
  transition: transform .4s;
  background: rgba(255, 0, 0, 0.3);
  margin: 20px;
  font-size: 12px;
  perspective: 1000px;
  cursor: pointer;
}

box:nth-child(2) {
  background: rgba(0, 0, 255, 0.3);
}
Run Code Online (Sandbox Code Playgroud)
<box>
  transform: perspective(1000px) translate3d(0,0,100px);
</box>
<box>
  transform: translate3d(0,0,100px) perspective(1000px);
</box>
Run Code Online (Sandbox Code Playgroud)

Tem*_*fif 4

在这两种情况下你都应该选择第perspective一个。如果您在最后添加它,则将首先进行翻译,而不考虑视角。

如果我们参考规范,我们可以看到变换矩阵是如何计算的:

变换矩阵是根据变换和变换原点属性计算得出的,如下所示:

  1. 从单位矩阵开始。

  2. 通过计算出的transform-origin的X和Y进行平移

  3. 从左到右乘以变换属性中的每个变换函数

  4. 通过转换原点的负计算 X 和 Y 值进行平移

正如您在步骤 (3) 中看到的,它是从左到右(这里是另一个问题,您可以在其中获取更多信息并了解为什么顺序很重要:Simulated transform-origin using translate

在要转换的元素中使用透视属性也是没有用的。

box:nth-child(1):hover {
  transform: perspective(1000px) translate3d(0, 0, -100px);
}

box:nth-child(2):hover {
  transform: perspective(1000px) translate3d(0, 0, 100px);
}

box {
  padding: 20px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-family: monospace;
  transition: transform .4s;
  background: rgba(255, 0, 0, 0.3);
  margin: 20px;
  /*perspective: 1000px;*/
  font-size: 12px;
  cursor: pointer;
}

box:nth-child(2) {
  background: rgba(0, 0, 255, 0.3);
}
Run Code Online (Sandbox Code Playgroud)
<box>
  transform: perspective(1000px) translate3d(0,0,100px);
</box>
<box>
  transform:  perspective(1000px) translate3d(0,0,100px);
</box>
Run Code Online (Sandbox Code Playgroud)

为了避免与顺序混淆,您可以在父元素中声明视角,但您需要注意来源,因为它不会相同:

box:nth-child(1):hover {
  transform:translate3d(0, 0, -100px);
}

box:nth-child(2):hover {
  transform:translate3d(0, 0, 100px);
}
body {
  perspective:1000px;
}
box {
  padding: 20px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-family: monospace;
  transition: transform .4s;
  background: rgba(255, 0, 0, 0.3);
  margin: 20px;
  font-size: 12px;
  cursor: pointer;
}

box:nth-child(2) {
  background: rgba(0, 0, 255, 0.3);
}
Run Code Online (Sandbox Code Playgroud)
<box>
  transform: perspective(1000px) translate3d(0,0,100px);
</box>
<box>
  transform:  perspective(1000px) translate3d(0,0,100px);
</box>
Run Code Online (Sandbox Code Playgroud)