CSS中绝对定位导致页面混乱的原因以及解决办法

131 篇文章 1 订阅

实现子元素在父元素中的绝对定位必须满足以下两个条件:

1、父元素要有相对定位属性(position:relative),

2、子元素设置绝对定位(position:absolute),并且同时加四个方向(top,bottom,left,right)的任意方向的属性值

 

子元素的绝对定位是包含块“containing block”的知识,

在 10.1 节 (http://www.w3.org/TR/CSS2/visudet.html#containing-block-details) 提到:
The position and size of an element's box(es) are sometimes calculated relative to a certain rectangle, called thecontaining block of the element. 

在下面的详细定义中,分情况说明了具有不同 position 属性的元素如何确定 containing block,其中第 4 点是绝对定位元素的情况:


If the element has 'position: absolute', the containing block is established bythe nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed', in the following way: 

  1. In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element. In CSS 2.1, if the inline element is split across multiple lines, the containing block is undefined.
  2. Otherwise, the containing block is formed by the padding edge of the ancestor.

If there is no such ancestor, the containing block is theinitial containing block.

从这里可以看到,一个元素的 containing block 是由其最近的 position 为 absolute / relative / fixed 的祖先元素决定的。
如果没有找到,则为 initial containing block。需要注意 initial containing block 并不是所谓的以 <body> 或是 <html> 定位的。

对这个 initial containing block 规范前文有描述:
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; ...

这就是说,initial containing block 是以整个 canvas (渲染内容的空间, http://www.w3.org/TR/CSS2/intro.html#canvas) 的坐标原点(左上)为基准,以 viewport (也就是浏览器视窗内渲染 HTML 的空间)为大小的矩形。


所以平时说的 position:absolute 元素相对最近的 position 为 absolute / relative / fixed 的祖先元素,或在找不到时基于根元素定位,这后面一半是错误的。

综上,子元素的绝对定位是相对于最近的position为absolute/relative/fixed的祖先元素,找不到时就相对于初始块(initial containing block)定位。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值