如何在使用翻译时支持相对位置:相对

它似乎使用transform: translateY(1px); 也会导致元素获得额外的position: relative; -行为。

有没有办法来支持这个?

这是codepen.io的一个例子。

我想将白盒绝对放在绿色盒子里,而不是父母(红色)盒子。


其中一个方案是置换/通过围绕一个元素否定父母的定位#three (在这种情况下,我加入了.displacement元素)。

绝对left: 0这个包装元素,并将其left: 0到父层(使用top: 0 / right: 0 / bottom: 0 / left: 0 )。 然后通过给元素赋予相对于父母的负翻译值来置换元素。

<div class="displacement">
    <div id="three"></div>
</div>
.displacement {
  -webkit-transform: translateY(-25px) translateX(-25px);
  transform: translateY(-25px) translateX(-25px);
  position: absolute;
  top: 0; right: 0;
  bottom: 0; left: 0;
  width: 200%; height: 200%;
}

在这样做时,该元件#three绝对相对于定位#one ,和父#two的翻译定位被有效地移动。

更新示例

.displacement {
  -webkit-transform: translateY(-25px) translateX(-25px);
  transform: translateY(-25px) translateX(-25px);
  position: absolute;
  top: 0; right: 0;
  bottom: 0; left: 0;
  width: 200%; height: 200%;
}
#three {
  background-color: white;
  height: 25px;
  width: 25px;
  position: absolute;
  left: 0;
  bottom: 0;
}

position:absolute (来自moz)不要为元素留出空间。 相反,将它定位在相对于其最接近的定位祖先或包含块的指定位置。 绝对定位的盒子可以有边距,它们不会与其他边缘一起折叠。

所以在你的情况下,最接近的祖先总是#two ,它不会继承任何位置属性,只是默认position: static; ...


如果你给了#two position:relative// or absolute位置,并将它放置在top: left:也许放置#three更容易:http://codepen.io/maio/pen/qEMJpY


这是一个不太理想的解决方法,但它适用于您现有的标记。

#two CSS更改为伪元素,添加这些样式:

#two::before {
  content: '';
  display: block;
}

更新了CodePen


改变你的标记之后,你的另一个解决方案是使用JavaScript来让three孩子成为第one元素:

document.querySelector('#one').appendChild(document.querySelector('#three'));

但是,它将不再继承元素two任何样式,如此CodePen中所示

这是一个有趣的阅读,它确认“转化一个元素的力量 - 增加位置:相对。”:http://meyerweb.com/eric/thoughts/2011/09/12/un-fixing-fixed-elements-with-css-转换/

不仅如此,它还会影响固定位置元素,这没有多大意义。

链接地址: http://www.djcxy.com/p/25255.html

上一篇: How to suspress the position: relative when using translate

下一篇: Accessing command history in QPython console for Android