跳轉到

建立 2025-02-25 更新 2026-09-11

displaypositionoverflow

這三個屬性經常一起出現:display 決定參與什麼排版模式,position 決定要不要離開正常流,overflow 決定內容溢出時怎麼辦。

display(顯示模式 / Display)

行為 常見元素
block 獨占一行,可設寬高 divpsection
inline 跟著文字流,設寬高多半無效 spanastrong
inline-block 不換行,但可設寬高 小按鈕、標籤
flex / inline-flex 彈性盒,見 Flex 導覽、工具列
grid / inline-grid 網格,見 Grid 版面、畫廊
none 移出渲染樹,不佔空間 關閉的選單
.tag {
  display: inline-block;
  padding: 0.15em 0.6em;
  border-radius: 999px;
}
隱藏方式 佔空間 可聚焦 / 可點
display: none
visibility: hidden
opacity: 0 是(需另關 pointer-events

position(定位 / Position)

搭配 top / right / bottom / left(或邏輯屬性 insetinset-blockinset-inline)使用。

參考點 是否離開文件流
static 預設,inset 無效
relative 自己原本的位置 否(視覺偏移,原位仍保留)
absolute 最近的定位祖先(非 static)
fixed 視覺視口(多數情況)
sticky 在滾動容器內切換相對 / 固定
.badge {
  position: absolute;
  top: 0.5rem;
  inset-inline-end: 0.5rem;
}

.page-header {
  position: sticky;
  top: 0;
  z-index: 20;
}

absolute 的包含區塊

往上找第一個 position 不是 static 的祖先。找不到就相對初始包含區塊(可視為頁面)。記得在父層加 position: relative(或 transform 等也會形成包含區塊)。

z-index

只對已定位元素(以及 flex/grid item)有意義。數字越大越靠上。比較發生在同一堆疊上下文;opacity < 1、transformfilter 都可能開新的堆疊上下文,導致子元素的 z-index 跳不出去。

.modal { position: fixed; inset: 0; z-index: 50; }
.toast { position: fixed; z-index: 60; }

建議用 CSS 變數做層級表:--z-header: 20--z-modal: 50,避免魔法數字。

overflow

行為
visible 預設,畫出去
hidden 裁切
clip 裁切且不可程式捲動
scroll 永遠留捲軸槽
auto 溢出才出現捲軸

可分開設:overflow-xoverflow-yoverflow: auto 的容器才是 sticky 常見的滾動祖先。

.code {
  max-height: 16rem;
  overflow: auto;
}

overflow 與 fixed / sticky

祖先若 overflow 不是 visible,可能成為滾動容器,讓 sticky 提早「黏在這個盒子裡」而不是視窗。transformfilter 也可能讓 fixed 改相對於該祖先。

常見組合

組合 效果
position: relative + 子 absolute 角標、圖片上的播放鈕
position: sticky + top: 0 表頭、章節小標
display: flex + overflow-x: auto 橫向滑動卡片列
overflow: hidden + border-radius 裁成圓角

總結

  • 排一排元件:Flex / Grid;疊在某個角落:absolute;跟著視窗:fixed;滾到定位再黏住:sticky
  • 隱藏分「不佔位」與「佔位」,選錯會造成版面跳動。
  • z-index 要搭配定位與堆疊上下文一起想。

傳統文字環繞見 浮動佈局;與定位的比較見 浮動與定位比較