【问题标题】:CSS transformed parent affect child positionCSS 转换的父级影响子级位置
【发布时间】:2015-08-05 08:56:18
【问题描述】:

为什么在转换父级时子级位置会受到影响?

我希望蓝色框保持在黄色框的右下角。但是当我翻译红色框时,蓝色框会移动到他的(红色)父级。

在现实生活中,红色方框代表我在 Angular 中的 ui-view。视图正在滑入和滑出。我无法更改 HTML 层次结构。

查看我的代码笔 https://codepen.io/benbesuijen/pen/GPOQjM

HTML

<div class="box-yellow">
    <div class="box-red">
        <div class="box-blue"></div>
    </div>
</div>

CSS

.box-yellow {
  background-color: yellow;
  position: relative;
  height: 200px;
  width: 200px;
}

.box-red {
  background-color: red;
  height: 100px;
  width: 100px;  
}

.box-blue {
  background-color: blue;
  bottom: 0;
  height: 50px;
  position: absolute;
  right: 0;
  width: 50px;
}

.box-move {
  transform: translateX(100%);
}

【问题讨论】:

  • 一定要使用translateX吗?您可能需要解释您的目标,因为我认为如果您不对这些框中的内容提供更多解释,您将会遇到更多问题?
  • 我认为这是一个问题,由转换时元素的堆叠上下文引起。在这里阅读更多:stackoverflow.com/questions/16148007/…
  • @Dan,我更新了我的描述。 Stewartside,谢谢,我会阅读它并希望我能找到解决方案。

标签: html css


【解决方案1】:

查看规范:The Transform Rendering Model

为“transform”属性指定“none”以外的值 在它所在的元素处建立一个新的局部坐标系 应用于。

这里的意思是蓝色元素将成为相对于具有变换的元素(红色父元素) - 而不是相对于视口(如常规静态元素)

但是,我们可以通过对黄色框应用变换来解决这种情况,并获得蓝色框的position: fixed

下面是一个例子:

var button = document.querySelector('button'),
    boxRed = document.querySelector('.box-red');

button.addEventListener('click', function() {
  boxRed.classList.toggle('box-move');  
});
.box-yellow {
  background-color: yellow;
  transform: translate(0, 0);
  float: left;
  position: relative;
  height: 200px;
  width: 200px;
}

.box-red {
  background-color: red;
  height: 100px;
  width: 100px;  
}

.box-blue {
  background-color: blue;
  position: fixed;
  bottom: 0;
  right: 0;
  height: 50px;
  width: 50px;
}

.box-move {
  margin-left: 50%;
}

button {
  margin-left: 20px;
}
<div class="box-yellow">
  <div class="box-red">
    <div class="box-blue"></div>
  </div>
</div>

<button>Translate red box</button>

希望这会有所帮助:)

【讨论】:

  • 我冒昧地为这个答案增添了一点趣味:)
  • @Ben Besuijen 如果您发现此答案有帮助,请务必将其标记为此类。还要感谢 Danield 改进答案:)
【解决方案2】:

我认为您唯一的方法是使用margin-left 并计算框的大小。比如:

button.addEventListener('click', function() {
   var boxRedWidth = boxRed.getBoundingClientRect().width;
   boxRed.style.marginLeft = boxRedWidth +"px"; 
});

这是由于 translateX 本质上使其成为 relative 位置对象,这意味着 .box-blue 作为其相对父级跳转到该位置对象中。 对于 margin-left.box-red 仍然是 static,这意味着它不会成为 box-blue 的相对父级。

【讨论】:

  • 整个变换属性使对象相对(也与缩放、旋转等有关)我无法弄清楚为什么这是正常的 CSS 行为。您的回答可以解决问题,但我不能使用它,因为边距在过渡时表现不佳。
  • 我认为您必须放弃性能提升,因为我认为没有其他方法。除非@Nemanja 回答对你有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 2018-08-23
  • 2015-10-30
  • 1970-01-01
相关资源
最近更新 更多