FOUNDATIONS PHASE 2 · 18
CSS Deep:從 Selector Match 到 Computed Style,再到 Layout
看到「CSS 沒生效」時,不應直接加 !important。Browser 會先 match selectors、跑 cascade、算 computed values,再參與 layout。每一步都有 evidence。
Learning outcomes
- 能追蹤 selector → cascade → computed style。
- 能解釋 specificity/source order/inheritance。
- 能用 box/layout evidence 找 overflow。
- 能判斷 Flex/Grid/normal flow 的責任。
1. Selector Match
.course-card p {
color: #334;
}
#featured p {
color: #900;
}第一步不是比較權重,而是確認 selector 是否真的 match 目標 element。
2. Cascade
p { color: black; }
.card p { color: blue; }
.card .warning { color: red; }Browser 依 origin/importance/specificity/source order 決定同一 property 的 winner。高 specificity 不是品質指標。
3. Computed Value
font-size: 1rem
width: 50%
line-height: 1.5Relative units 需要 context 才能算出最終值。DevTools Computed 比只看 stylesheet 更接近 Browser 真正使用的結果。
4. Box / Layout
.layout {
display: grid;
grid-template-columns:
16rem 1fr;
gap: 1rem;
}Layout 不是 selector 的下一種語法;它是元素在可用空間中如何分配尺寸/位置的演算法。
5. Overflow 常是上游 Constraint 問題
固定 width、min-width、長字串、absolute positioning 都可能讓子元素超出 containing block。直接加 overflow:hidden 可能只是把 evidence 蓋掉。
Project checkpoint:Course Workspace Layout
desktop:
sidebar | content
small viewport:
content only
sidebar becomes top section
card grid:
auto-fit + minmax目標不是「在某支手機看起來剛好」,而是 layout constraints 在多種 viewport 都成立。
Debug evidence
- Styles:rule 有沒有 match/被劃掉?
- Computed:最終 property 是多少?
- Box Model:哪個盒子超出?
- Layout panel:Flex/Grid tracks 如何分配?
Knowledge check
- CSS rule 不生效時第一件事是加 specificity 嗎?
- Computed style 和 stylesheet declaration 差在哪?
- overflow-x:hidden 可能掩蓋什麼?
- 用 DevTools 找出一個 layout constraint。