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

查看:293
本文介绍了css - 请教一个关于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%

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

解决方案

纠正错误。
绝对定位相对其包含块定位,其中有一个包含块叫初始包含块,即无定位父级,相对于初始包含块。
初始包含块在实现上是一个和视口重叠的区域。
怎么证明呢?
给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.

这篇关于css - 请教一个关于absolute定位top值为百分比时的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆