文章將陸續整理並更新至個人部落格。
所有元素(element)都可以生成盒子(box),什麼類型的元素,生成什麼類型的盒子,盒子可以裝盒子,整個版面都是盒子!這些盒子依照自己所屬的格式化上下文進行排列,不同的格式化上下文有不同的佈局規則,格式化上下文是一個「佈局環境」。
上一篇文章中介紹了塊格式化上下文(BFC),這篇將介紹行內格式化上下文(IFC),Let's go!
直接看一段 W3C 規範對於 IFC 的定義吧,別忘了格式化上下文是一種「佈局環境」。
摘自 W3C
In an inline formatting context, boxes are laid out horizontally, one after the other, beginning at the top of a containing block. The rectangular area that contains the boxes that form a line is called a line box.
The width of a line box is determined by a containing block and the presence of floats.
也就是說,處在 IFC 佈局環境下的元素(盒子),會有以下的佈局規則:
由包含塊(containing block)頂部開始,元素一個接一個呈現水平排列。
每一行稱為一個 line box。 (之後再介紹)
line box 的寬度取決於包含塊與浮動元素(浮動元素會擠壓 line box)。
註: line box 過於複雜,在此先不多作介紹。
有沒有似曾相似的感覺?
沒錯~
其實大家所熟悉的 display: inline 與 inline-block 就是 IFC 的佈局規則。
原因是 display: inline 與 inline-block 皆是行內級元素(inline-level element)之一,而所有行內級元素本身都會參與 IFC。
那還有哪些元素是屬於行內級元素,會參與 IFC 呢?
這取決於 display 的外部顯示(outer display type)。
摘自 W3C 對於 display 外部顯示與內部顯示的定義
The display property defines an element’s display type, which consists of the two basic qualities of how an element generates boxes:
the inner display type, which defines (if it is a non-replaced element) the kind of formatting context it generates, dictating how its descendant boxes are laid out. (The inner display of a replaced element is outside the scope of CSS.)
the outer display type, which dictates how the principal box itself participates in flow layout.
也就是說,
display 的內部顯示:決定元素對內生成何種格式化上下文(formatting context),這會影響其後裔元素的佈局方式,而會生成何種類型的格式化上下文,取決於其 container box 的類型。
display 的外部顯示:生成一個主盒子(principal box),用以決定元素本身對外參與何種方式的佈局。
下表中可以清楚看出哪些 display 值會變成什麼類型的元素(生成什麼類型的盒子)。


註:
① 什麼類型的元素(element)就會生成什麼類型的盒子(box)。
② block container box 由 block container element 生成。
③ block container box 可同時建立 BFC 與 IFC。
④ text-align 可控制 block container 裡的行內級元素。
⑤ block-level box 本身會參與 BFC。
⑥ inline-level box 本身會參與 IFC。
其實 BFC 和 IFC 真的無所不在,只是你沒有察覺而已~
他們又被稱為是正常流(normal flow)唷~
掰拉~
此文章為學習筆記,如有理解錯誤的地方,煩請告知,感謝~
W3C-Inline formatting contexts
W3C-Controlling box generation
W3C-Box Layout Modes: the display property