FE Interview Hub
CSS中階

請解釋 CSS position 有什麼值和作用?

AI 練習作答

CSS position 的五個值

static(預設)

.box { position: static; } /* 預設值 */
  • 依照正常文件流排列
  • top / right / bottom / left / z-index 無效

relative

.box {
  position: relative;
  top: 10px;
  left: 20px;
}
  • 相對於自身原本位置偏移
  • 仍保留原本佔用的空間(不影響其他元素)
  • 常作為 absolute 子元素的定位參考父容器

absolute

.parent { position: relative; }

.child {
  position: absolute;
  top: 0;
  right: 0;
}
  • 相對於最近的 positioned 祖先元素(非 static)定位
  • 脫離文件流,不佔空間
  • 若找不到 positioned 祖先,則相對於 <html> 定位

fixed

.navbar {
  position: fixed;
  top: 0;
  width: 100%;
}
  • 相對於**瀏覽器視窗(viewport)**定位
  • 捲動頁面時保持固定位置
  • 脫離文件流

sticky

.header {
  position: sticky;
  top: 0;
}
  • 結合 relativefixed:正常情況下隨頁面捲動,滾動到指定位置後固定
  • 不完全脫離文件流

各值比較

定位參考 佔據空間 脫離文件流
static 文件流
relative 自身原位
absolute positioned 祖先
fixed Viewport
sticky 捲動容器 部分

✦ AI 模擬面試

輸入你的答案,AI 即時分析精準度與改進空間

登入後即可使用 AI 評分