使用变换缩放时定位兄弟姐妹 属性

Position the siblings when using scaling with transform property

我正在对一个除法实施 CSS 变换 属性,并且有一个用例,根据缩放比例移动位于它旁边的兄弟姐妹。

我尝试调整位置但没有奏效,我认为这就是转换功能。我可能错了,所以想在这里再试一次。

.parent{
  display:flex;
}
.childA{
  padding: 1rem;
  width: 20rem;
  background: lightblue;
}
.childA:hover {
  transform: scale(5);
  transform-origin:top left;
  z-index:0;
}
.childB {
  border: solid 1px;
  color:white;
  padding: 1rem;
  background: red;
  z-index:1 /*Not sure why I had to do this too*/
}
<div class='parent'>
   <div class='childA'>Child A scales</div>
   <div class='childB'>I want to move when scaled</div>
</div>

请看一下这个游乐场,子元素就在那里,但我需要它向右移动 https://codepen.io/frank-underwood/pen/jOOmLJO?editors=1100

.parent{
  display:flex;
}
.childA{
  padding: 1rem;
  width: 20rem;
  background: lightblue;
}
.childA:hover {
  transform: scale(5);
  transform-origin:top left;
  z-index:0;
}

.childA:hover + .childB {
  transform: translateX(calc(22rem * 4));
}
.childB {
  border: solid 1px;
  color:white;
  padding: 1rem;
  background: red;
  z-index:1
}
<div class='parent'>
   <div class='childA'>Child A scales</div>
   <div class='childB'>I want to move when scaled</div>
</div>

我不确定您要将它移动多少或移动到哪里.. 下面是让它在您的缩放元素悬停时移动的代码。我正在使用相邻的 CSS 组合器来实现这一点。当您将鼠标悬停在 ChildA 上时,可以为相邻的 ChildB 提供一组属性。

至于为什么必须在 .childB 上放置 z-index 是因为转换会创建一个新的堆叠上下文。即使 .childA 在您的 HTML 中出现在 .childB 之前,转换本质上还是将 .childA 带到了一个新层。因此,您必须设置 .childB 的 z-index。

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

这里有一些关于堆叠上下文的读物。了解这些工作原理以及产生新功能的原因非常重要。

edit 您可以根据悬停的元素计算平移,它会持续移动。我在宽度上加了 2rem,因为两边都有 1rem 的填充。 22rem * 4 而不是 5 因为 scale(1) = 22rem.

变换影响类似于绝对位置,因此您可以增加宽度并使用 calc 方法可以设置它增加的次数;

.parent{
  display:flex;
}
.childA{
  padding: 1rem;
  width: 20rem;
  background: lightblue;
}
.childA:hover {
  width: calc(20rem * 5);/*here you can change 5*/
  transform-origin:top left;
}
.childB {
  border: solid 1px;
  color:white;
  padding: 1rem;
  background: red;
}
<div class='parent'>
 <div class='childA'>Child A scales</div>
 <div class='childB'>I want to move when scaled</div>
</div>

如果您能够调整 html 结构,您可以轻松地做到这一点:

.parent{
  display:flex;
}
.leftDiv{
  background:yellow
}
.childA{
  padding: 1rem;
  background: lightblue;
  position:relative;
}
.childA:hover {
  transform: scale(2);
  transform-origin:top left;
  z-index:0;
}
.childA:hover .childB {
  transform: scale(0.5);
  transform-origin:top left;
}
.childB {
  border: solid 1px;
  color:white;
  padding: 1rem;
  background: red;
  position:absolute;
  left:100%;
  top:0;
  bottom:0;
  white-space:nowrap;

}
<div class='parent'>
  <div class='leftDiv'>I will just stay here</div>
 <div class='childA'>Child A scales
   <div class='childB'>I want to move when scaled</div>
 </div>
</div>