使用CSS缩放/矩阵不保持背景与元素对齐

Using CSS Scale/Matrix doesn't keep background aligned with elements

本文关键字:背景 元素 对齐 缩放 CSS 使用      更新时间:2023-09-26

我有一个div的虚线背景。有一些子元素。如果我应用以下CSS:

transform:scale(x);

则元素不再与背景对齐,即使该比例设置为1(我也尝试过这个变换:矩阵(…))。

我做了一个小提琴来演示我的意思:https://jsfiddle.net/gawdhfpc/

.container {
  width: 500px;
  height: 500px;
  background: blue;
}
.toTransform {
  width: 100%;
  height: 100%;
  background-image: radial-gradient(black 3px, white 3px);
  background-size: 100px 100px;
  /* comment to see what it should look like */
  transform: scale(1);
}
.child {
  height: 100px;
  width: 100px;
  background: red;
  position: absolute;
  top: 258px;
  left: 258px;
}
<div class="container">
  <div class="toTransform">
    <div class="child">
    </div>
  </div>
</div>

如果您删除css变换,您将看到子元素与背景上的点对齐。一旦转换应用,子对象被移动并且不再与点对齐。为什么会发生这种情况?有什么办法能解决这个问题吗?我需要让用户放大/缩小,我一直在做这个与D3和缩放/翻译。

我有一个解决方案,但我实际上不知道是什么导致了潜在的问题。

你的红色方块子节点有position:absolute,但是它没有position:relative的父节点,所以它的位置绝对相对于文档本身。当你应用一个变换时,不管出于什么原因,它的位置绝对相对于。totransform,在你的例子中,由于自然的边距和填充,它与文档的偏移量为~10像素。本质上,通过添加变换,它看起来就像您已经隐式地将position:relative应用于.toTransform 一样。

如果你一开始就这么做了,添加/移除变换不会产生干扰,比如

.toTransform {
  position:relative;
}
.child {
  /* drop each value by ~10px */
  top: 248px;
  left: 248px;
}

现在无论你是否进行变换,正方形的位置都不会受到影响

可能相关:为什么position: relative"干涉"transform: scale"?