[css 規範] 包含塊(containing block)

簡介

包含塊是 css 中的一個很重要的概念, 簡單來講一個元素應該在什麼位置展現和定位? 應該在包含塊內, 那麼如何找到給定元素的包含塊, 即是該章節討論的問題.css

另外這篇文章不是源規範的標準翻譯, 不過重要的部分我就忽略了, 修改了一些表格之類的東西, 還加入了一些個人思考. 若是追求嚴謹能夠去查看源規範.html

包含塊(containing block)

https://drafts.csswg.org/css2...

元素所對應的盒子(element's box) 的位置和大小有時是相對於特定的矩形進行計算的, 這個矩形被稱爲這個元素的包含塊. 包含塊的定義以下:spa

  1. 根元素所在的包含塊是一個被稱爲初始包含塊的矩形. 對於連續媒體,它具備視口(viewport)的尺寸,並錨定在畫布原點;它是分頁媒體的頁面區域。初始包含塊的「direction」屬性與根元素的「direction」屬性相同。
  2. 對於其餘元素,若是元素的 positiionrelativestatic ,由離它最近的塊容器(block container)的內容區域(content area)的邊緣創建.
  3. 若是元素的定位使用 fixed 包含塊對於連續媒體由視口創建, 對於分頁媒體由頁面區域創建.
  4. 若是元素使用了 absolute 定位, 則包含塊由最近使用了 absolute fixed relative 的父元素經過下列方式創建翻譯

    1. 若是該父元素是內聯元素(inline element),則包含塊是圍繞該父元素的第一個和最後一個內聯盒子的 padding 盒子生成的邊界盒子。 在CSS 2中,若是內聯元素分割成了多行,這種狀況下包含塊沒有被定義。 **
    2. 不然就是該父元素的 padding 的邊緣
    3. 若是不存在使用定位的父元素那麼包含塊就是初始包含塊

** 對應的狀況可能入下方代碼所示:code

<span style='background:aqua;position:relative;padding:10px'>hello <em style="background:white;position:absolute;top:0;left:0;">world</em>!</span>

In paged media, an absolutely positioned element is positioned relative to its containing block ignoring any page breaks (as if the document were continuous). The element may subsequently be broken over several pages.htm

For absolutely positioned content that resolves to a position on a page other than the page being laid out (the current page), or resolves to a position on the current page which has already been rendered for printing, printers may place the contentelement

  • on another location on the current page,
  • on a subsequent page, or
  • may omit it.

在下面的例子中的包含塊沒有使用任何定位:get

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
   <HEAD>
      <TITLE>Illustration of containing blocks</TITLE>
   </HEAD>
   <BODY id="body">
      <DIV id="div1">
      <P id="p1">This is text in the first paragraph...</P>
      <P id="p2">This is text <EM id="em1"> in the 
      <STRONG id="strong1">second</STRONG> paragraph.</EM></P>
      </DIV>
   </BODY>
</HTML>

對於頁面中的元素, 指出對應的包含塊:it

元素 包含塊 知足條件
html 初始包含塊 根元素
body html 2
div1 body 2
p1 div1 2
p2 div1 2
em1 p2 2
strong1 p2 2

設置如下 css:io

#div1 { position: absolute; left: 50px; top: 50px }
#em1  { position: absolute; left: 100px; top: 100px }

對於頁面中的元素, 指出對應的包含塊:

元素 包含塊 知足條件
html 初始包含塊 根元素
body html 2
div1 html 4.c
p1 div1 2
p2 div1 2
em1 div1 4.b
strong1 ** em1 2

** 這裏在規範中很模糊至少我沒有找到完整的相關描述. 總的來說 strong1 的包含塊是 em1 的緣由是 em1 絕對定位了, 而條件 2 的說法是相對於 block container 的, 可是在規範中, 絕對定位元素僅僅被描述爲能夠創建塊級格式化上下文, 而塊級格式化上下文並無說明內部是否必須都是是塊級盒子(block-level box), 塊級盒子部分也只說明它能夠參與塊級格式化上下文的創建, 最關鍵的是 block container 的定義是僅僅能包含塊級盒子, 因此沒有關鍵證據指出 em1 此時是 block container.

因此產生一個問題 "containing box 是否就是 block container" ?

問題更新

https://www.w3.org/TR/CSS22/v...

在 css2.2 規範中指明瞭 block-level 就是 block container.

因此文字如今成爲了:

問題在於 containing box 是否就是 block container

以及 containing box 是否就是 block-level box

另外我查閱了最新的 CSS3 規範草案和定位章節目前沒有找到合理的解釋.

相關文章
相關標籤/搜索