CSS: Layout

date
Apr 22, 2024
slug
css-layout
status
Published
tags
Frontend
CSS
summary
翻閱了幾篇 MDN 的文章後,決定紀錄一下幾個重要的 CSS 概念
type
Post
翻閱了幾篇 MDN 的文章後,決定紀錄一下幾個重要的概念

Box Model

CSS 的世界裡,Box 可以拆分為四個區塊,由內而外分別為:
  • Content Area
  • Padding Area
  • Border Area
  • Margin Area
notion image
而常見的 CSS 屬性 box-sizing 便是決定元素的寬高需要涵括到哪些區域,預設的 content-box 只會計算進 Content Area,如果設定成 border-box 的話則會涵括 Content, Padding, Border 三塊。
💡
content-box 容易造成計算上的困難,當想要用寬度來定義容器大小時,就需要小心 padding 和 border 不在寬度所限的範圍內!

Containing Block

Containing block 是指元素的母容器,根據 position 屬性可拆分成以下三種情形:

static / relative / sticky

最近的 block container (or BFC) 的 content box

absolute

最近的非 position: static container 的 padding box

fixed

initial containing box (viewport or page)
 
💡
當 position 為 absolute 或 fixed 時,外部容器如果有 transform / will-change / filter 等屬性,也會優先被當作 containing block,詳細的規則可以參考 MDN 上的 Layout and the containing block
值得一提的是 containing block 在計算元素大小時有重要的功用,使用 percentage 來表示寬高時都是使用 containing block 來當作基準值的。

BFC & IFC

BFC 和 IFC 分別是 Block Formatting Context 和 Inline Formatting Context。前者會由上到下排列,後者是由左至右。
值得一提的是 IFC 上使用 margin 使用影響左右,而垂直方向的 padding / border 雖然能生效,但並不會改變排版。

Inner & Outer Display Type

決定本身和子元素如何佈局

Out of Flow

使用到
  • float
  • position: absoluteposition: fixed
會產生新的 BFC,其內部的 children 也都不會受原本外部的 Layout 影響
💡
可以使用 display: flow-root 來開一層新的 BFC
 

© maxam 2023 - 2024