問題:
如果子元素設置絕對定位(absolute),父元素需要設置相對定位(relative),否則子元素就不知道會飄到哪去了。
本着知其然還要知其所以然的學習態度,就去Google了,得到了一些見解,以下:
一、表
實現子元素在父元素中的絕對定位必須滿足以下兩個條件:
1、父元素要有相對定位屬性(position:relative),
2、子元素設置絕對定位(position:absolute),並且同時加四個方向(top,bottom,left,right)的任意方向的屬性值
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8" />
<title></title>
<style type="text/css"> #main{ width:500px; height:600px; border:1px solid black; position:relative; background:pink;
} #one,#two{ width:100px; height:100px;
} #one{ background:blue; position:absolute; top:100px; left:100px;
} #two{ background:yellow; position:absolute; top:200px; left:200px;
}
</style>
</head>
<body>
<div id="main">
<div id="one">1</div>
<div id="two">2</div>
</div>
</body>
</html>
這個理解應該是從代碼的書寫形式總結的,雖然能滿足頁面要求,但其實是有謬誤的。具體看下面分析。
二、里
子元素的絕對定位是包含塊“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.
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:
- 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.
- Otherwise, the containing block is formed by the padding edge of the ancestor.
從這里可以看到,一個元素的 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 的空間)為大小的矩形。
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)定位。