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

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

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)定位。

猜你喜欢

转载自blog.csdn.net/weixin_43727372/article/details/91642498