请教一个关于absolute定位top值为百分比时的问题

absolute定位元素,top值为百分比,如果我理解的没错的话,这个百分比是相对于最近的父(祖先)绝对定位或相对定位元素的高度的,即如果该父(祖先)元素高度为100px,top值为50%,则top的计算值为50px;如果找不到这个父元素,则是相对于html根元素;现在代码如下:

<body>
    <main>
        <h1>Am I centered yet?</h1>
        <p>Center me . please!</p>
    </main>
</body>
html,
body {
    margin: 0;
    padding: 0;
}
main {
    background: #eee;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    /*transform: translate(-50%, -50%);*/
}

按照上面的说法,此时main的百分比应该是相对于html元素的,而html的高度为0,那么top的计算值不是应该为0才对吗,而实际情况是,top的计算值是屏幕高度的50%

clipboard.png

请问,是我哪里想错了吗?

阅读 7k
4 个回答

纠正错误。
绝对定位相对其包含块定位,其中有一个包含块叫初始包含块,即无定位父级,相对于初始包含块。
初始包含块在实现上是一个和视口重叠的区域。
怎么证明呢?
给body、html宽高都设置成1px,而内部元素top:50%;拖动窗口大小观察。

w3c推荐标准

The containing block in which the root element lives is a rectangle called the initial containing block. For continuous media, it has the dimensions of the viewport and is anchored at the canvas origin; it is the page area for paged media. The 'direction' property of the initial containing block is the same as for the root element.

题主上面说的说法来自哪的?

http://learnlayout.com/positi...

absolute is the trickiest position value. absolute behaves like fixed except relative to the nearest positioned ancestor instead of relative to the viewport. If an absolutely-positioned element has no positioned ancestors, it uses the document body, and still moves along with page scrolling. Remember, a "positioned" element is one whose position is anything except static.

https://developer.mozilla.org...

我翻看的两个,都是指body

absolute的元素百分比的计算是相对于其包含块的padding边界所形成的盒(框)来计算的。
main 包含它的块是body
自测试body 样式为:

clipboard.png

main style为:

clipboard.png

所以没毛病



    .one {
      background-color: palevioletred;
      outline-color: yellow;
      outline-style: solid;
      width: 100px;
      height: 100px;
     /* position: absolute;
      top: 80%;
      left: 50%;
      transform:translate(-50%,-50%);
      */
      
    }
    .two {
      background-color: lightblue;
      outline-color: blue;
      outline-style: solid;
      width: 50%;
      height: 50%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform:translate(-50%,-50%);
    }
 <div class="one">1
    <div class="two">2</div>
  </div>

absolute是指定元素相对于最近的position值为非 static 定位祖先元素的偏移的。
上面的代码,.oneposition: absolute;与不加position: absolute;是完全不一样的。
1

2

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题