如何使用css透视图将元素定位在正确的3d位置

时间:2018-02-13 23:50:14

标签: css webkit-perspective

我试图找到一种在给定角度放置的照片元素上映射元素的方法。笔记本电脑的照片就是一个很好的例子,我想在屏幕上方映射一个元素(视频,图像或其他),例如,让我们说一个视频循环等。

这项任务似乎很容易,但我发现它非常棘手,因为我无法通过变换旋转,缩放,平移甚至倾斜来找到如何正确解决它。

enter image description here

这是我想要实现的代码示例,over元素是SPAN绿色

HTML:

    <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div>
    <span></span>
    <img src="http://www.thesugarrefinery.com/wp-content/uploads/2015/08/sugar-macbook-7-5-perspective.png" />
  </div>

</body>
</html>

的CSS:

div {
  position: relative;
}
span {
  background: green;
  width: 350px;
  height: 200px;
  position: absolute;
  top: 0;
  left: 0;
  perspective: 250px;
  transform: rotateX(0deg) rotateY(40deg) rotateZ(0deg) skewX(-10deg) translateX(220px) translateY(25px) scale(.94);
  opacity: 0.5;
}
img {
  width: 500px;
  height: auto;
}

和片段:

&#13;
&#13;
div {
  position: relative;
}
span {
  background: green;
  width: 350px;
  height: 200px;
  position: absolute;
  top: 0;
  left: 0;
  perspective: 250px;
  transform: rotateX(0deg) rotateY(40deg) rotateZ(0deg) skewX(-10deg) translateX(220px) translateY(25px) scale(.94);
  opacity: 0.5;
}
img {
  width: 500px;
  height: auto;
}
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div>
    <span></span>
    <img src="http://www.thesugarrefinery.com/wp-content/uploads/2015/08/sugar-macbook-7-5-perspective.png" />
  </div>
  
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

perspective需要添加到父级,而不是子级。其余的是细节:

&#13;
&#13;
span {
  background: green;
  width: 256px;
  height: 176px;
  position: absolute;
  top: 0;
  left: 0;
  transform: rotateX(1deg) rotateY(-7deg) rotateZ(-1deg) skew(-11.25deg, 1.5deg) translate(233px, 37px);
  opacity: 0.5;
}

div {
  position: relative;
  perspective: 400px;
  width: 1200px;
}

img {
  width: 500px;
  height: auto;
}

body {
  overflow-x: hidden;
}
&#13;
<div>
  <span></span>
  <img src="http://www.thesugarrefinery.com/wp-content/uploads/2015/08/sugar-macbook-7-5-perspective.png" />
</div>
&#13;
&#13;
&#13;