有一个position值为absolute的div,他的祖先元素里没有任何定位属性,或者他的父元素就是body。 当这个div的bottom值为0的时候,他应该被定位到哪个位置? 这个大家都知道在最下面。 现在条件稍微修改一下,给body和html一个height的值,给大一些,就10000px吧。 现在这个div的位置应该在哪?
就像下面的代码,这个div依然被定位在了屏幕的底部,和fixed值“一样”的表现。只不过这个“一样”是暂时的,拖动滚动条就露底了,div滚动了上去,死死的定位在了第一屏底部的位置。
<!DOCTYPE html>
<html>
<head>
<title>绝对定位bottom值为0的位置问题-caihong.cc</title>
<style>
*{
margin: 0;
padding:0;
}
html,body{
height: 10000px;
}
.position-el{
width: 100px;
height: 100px;
background: #ff0;
position: absolute;
bottom: 0;
}
</style>
</head>
<body>
<div class="position-el"></div>
</body>
</html>
提示:你可以先修改部分代码再运行。
应该不少同学都知道这个表现,我问过几个朋友,他们也知道绝对定位的元素bottom为0的时候会定位到屏幕底部。但是细问原理的时候都没能讲出来。
为什么他没有定位到文档的最底部?
我跑到w3.org从absolute属性开始扒。
9.6 Absolute positioning In the absolute positioning model, a box is explicitly offset with respect to its containing block.
这一条刚入门的时候就知道,绝对定位的元素相对于他的包含块位移。现在的问题是div的包含块是谁,于是我继续去扒包含块。
10.1 Definition of “containing block” The position and size of an element’s box(es) are sometimes calculated relative to a certain rectangle, called the containing block of the element. The containing block of an element is defined as follows: 1.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.
运气真好,第一条信息就很足了,根元素所在的 containing block 被称为 initial containing block,大小和 viewport 相同,原点与 canvas 重合。
到这里好像答案已经出来了,不过我还是顺着paged media继续多扒了一点
13.2 Page boxes: the @page rule The page box is a rectangular region that contains two areas: The page area. The page area includes the boxes laid out on that page. The edges of the first page area establish the rectangle that is the initial containing block of the document. The canvas background is painted within and covers the page area. The margin area, which surrounds the page area. The page margin area is transparent.
现在才算是把bottom:0 的定位问题逐步弄清楚了。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有