我想在 CSS 中使用 transform: translate
模拟 transform-origin
的属性。
According to MDN ,这是很有可能的:
This property is applied by first translating the element by the negated value of the property, then applying the element's transform, then translating by the property value.
但是,当我尝试时,我得到了不正确的结果。这两个矩形显然不一样:
.origin {
transform-origin: 100px 100px;
transform: translate(100px, 0px) scale(2) rotate(45deg);
}
.translate {
transform: translate(-100px, -100px) translate(100px, 0px) scale(2) rotate(45deg) translate(100px, 100px);
}
.box {
background-color: red;
width: 100px;
height: 100px;
}
.container {
float: left;
margin: 100px;
width: 250px;
height: 250px;
background-color: rgba(0, 0, 0, 0.1);
}
<div class="container">
<div class="box origin">
</div>
</div>
<div class="container">
<div class="box translate">
</div>
</div>
我已经尝试了很长一段时间没有运气地寻找答案,在我看来它应该比较简单,我就是想不通。
最佳答案
你差不多好了,但有两个错误。您需要反转翻译,并且需要更改第二个翻译的 transform-origin
。
如果查看文档,您会看到用于转换原点的引用是元素的左上角,转换原点的默认值是center
。所以我们需要为两者提供相同的引用。
.origin {
transform-origin: 50px 50px;
transform: rotate(45deg) scale(2);
}
.translate {
transform-origin:0 0;
transform:translate(50px, 50px) rotate(45deg) scale(2) translate(-50px, -50px);
}
.box {
background-color: red;
width: 50px;
height: 50px;
}
.container {
display: inline-block;
margin: 30px;
width: 150px;
height: 150px;
background-color: rgba(0,0,0,0.1);
}
<div class="container">
<div class="box origin">
</div>
</div>
<div class="container">
<div class="box translate">
</div>
</div>
这里来自specification :
The transformation matrix is computed from the transform and transform-origin properties as follows:
Start with the identity matrix.
Translate by the computed X and Y of transform-origin
Multiply by each of the transform functions in transform property from left to right
Translate by the negated computed X and Y values of transform-origin
你需要注意措辞!您可能会发现 MDN 与规范自相矛盾,但事实并非如此,因为翻译元素(如 MDN 中所述)和翻译元素的来源之间存在差异 或本地坐标(如规范中所述)。
例如,将元素平移 -50px 相当于将其局部坐标(原点)平移 +50px。
您还需要注意“从左到右相乘”,因为它可能会造成混淆。如果我们在示例 3 中引用相同的规范,我们有:
div {
height: 100px; width: 100px;
transform: translate(80px, 80px) scale(1.5, 1.5) rotate(45deg);
}
This transformation translates the local coordinate system by 80 pixels in both the X and Y directions, then applies a 150% scale, then a 45° clockwise rotation about the Z axis. The impact on the rendering of the element can be intepreted as an application of these transforms in reverse order: the elements is rotated, then scaled, then translated.
所以从左到右相乘并不意味着从左到右应用,这在某种程度上解释了反转您应用的转换以模拟 transform-origin
的需要:
关于css - 使用 translate 模拟 transform-origin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51077632/