Absolutely positioned element positions relatively to transformed element

回眸只為那壹抹淺笑 提交于 2019-12-06 20:49:35

Basically because any element with the transform property applied, automatically triggers a new stacking order: https://developer.mozilla.org/en-US/docs/Web/CSS/transform

"If the property has a value different than none, a stacking context will be created. In that case the object will act as a containing block for position: fixed elements that it contains."

Here is some extra info about stacking context: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

The CSS spec states that defining a transform on an element creates a containing block:

For elements whose layout is governed by the CSS box model, any value other than none for the transform results in the creation of both a stacking context and a containing block.

And that (see spec):

In the absolute positioning model, a box is explicitly offset with respect to its containing block.




The key here is that setting the transform property of an element to anything other thant none, creates a new containing block; stacking contexts have nothing to do with the way the element is positioned.

See examples in the below snippet.

body {
  padding-top: 100px;  
}

.containing-block,
.stacking-context {
  height: 50px;
  padding-top: 50px;
}

.containing-block {
  background-color: hotpink;
  /* transform with a value other than none defines both a containing block and a stacking context. */ 
  transform: scale(1);
}

.stacking-context {
  background-color: orange;
  /* opacity with a value other than 1 defines a stacking context but no containing block. */
  opacity: .99;
}

.abs{
  position: absolute;
  top: 0;
    
  padding: 10px;

  background-color: dodgerblue;
}
<body>
  <div class="containing-block">1: transform: scale(1);
    <div class="abs">1: Containing block example</div>
  </div>

  <div class="stacking-context">2: opacity: .99
    <div class="abs">2: Stacking context example</div>
  </div>
</body>

If you apply the transform to .main instead of div it seems to work as expected.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!