LESSON-04 · TOPIC 01
繼承與非繼承屬性
能用 Computed 判斷文字 color 會由父層傳給子層,而 border-width 預設不會。
code-edit選擇器、繼承與無效宣告|繼承與非繼承屬性本頁只練一個責任
本頁只練什麼
能用 Computed 判斷文字 color 會由父層傳給子層,而 border-width 預設不會。
若把所有屬性都當成會繼承,常會在子元素重複補樣式,或誤判邊框沒有出現是 selector 失效。
要修改的檔案:files/starter/style.css
定位:在 Elements 選取 data-inheritance-child,先讀 Computed color 與 border-top-width。|依 starter-1 定位,只修改「繼承與非繼承屬性」的責任。
任務情境
先結果,再原理;完成後要能說出自己看見的證據。
現在的問題
服務卡父層已有品牌文字色與外框,但卡片內的說明文字只有顏色相同、沒有自己的邊框。
起始狀態:父層 color 為 rgb(23, 50, 77)、border 為 4px;子層沒有 border-width 宣告。
完成後要看到
子層 color 與父層相同;border-top-width 初始為 0px,加入明確 inherit 後才成為 4px。
驗收證據:實驗 before=0px、after=4px;同一子層的 Computed color 與父層相同
何時會用到
子元素沒有自行宣告,但 Computed 值仍受祖先影響,或父層有邊框而子層沒有時。
常見混淆:繼承不是 cascade 勝負;cascade 先決定元素自己的指定值,繼承是在缺少適用宣告時取得父層值。
觀念與最小範例
這段程式是理解起點,不是要你直接跳過 Starter。
繼承與非繼承屬性 Inherited and non-inherited properties
文字顏色像家族特徵,子層通常會沿用;邊框像各自的外框,不會自動傳下去。
正式說法:CSS property 具有不同的 inherited initial definition;color 預設繼承,border-width longhands 預設不繼承。
.parent { color: #17324d; border: 4px solid; } .child { border-width: inherit; }
三步完成本主題
每一步都留下可觀察結果;如果沒看到,先看「卡住先查」。
Step 1|先看見目前缺口,不急著貼答案。
檔案:files/starter/style.css 定位:在 Elements 選取 data-inheritance-child,先讀 Computed color 與 border-top-width。
要做:先重新載入 Starter,記錄目前畫面、DOM、Computed、Console 或文件內容。
預期:能指出「在 Elements 選取 data-inheritance-child,先讀 Computed color 與 border-top-width。」目前的缺口。
證據:保存 files/starter/style.css 的目前狀態,並指出下一步只會修改哪個檔案責任。
卡住先查:確認開啟的是 files/starter/style.css,且定位到 在 Elements 選取 data-inheritance-child,先讀 Computed color 與 border-top-width。。
Step 2|只修改本主題的一個責任。
檔案:files/starter/style.css 定位:在 Elements 選取 data-inheritance-child,先讀 Computed color 與 border-top-width。
要做:執行實驗先讀子層 border-top-width,再切換 .inherit-border 令 border-width 明確使用 inherit。
預期:子層 color 與父層相同;border-top-width 初始為 0px,加入明確 inherit 後才成為 4px。
證據:實驗 before=0px、after=4px;同一子層的 Computed color 與父層相同
卡住先查:在 Elements 選取 data-inheritance-child,先讀 Computed color 與 border-top-width。
Step 3|重新載入並以證據驗收,不以『看起來差不多』判定完成。
檔案:files/starter/style.css 定位:在 Elements 選取 data-inheritance-child,先讀 Computed color 與 border-top-width。
要做:重新整理頁面,再逐項比對預期結果與 evidence。
預期:子層 color 與父層相同;border-top-width 初始為 0px,加入明確 inherit 後才成為 4px。
證據:實驗 before=0px、after=4px;同一子層的 Computed color 與父層相同
卡住先查:在 Elements 選取 data-inheritance-child,先讀 Computed color 與 border-top-width。
觀察示範
這個示範只讓你看懂概念,不會替你修改 Starter,也不會自動宣告完成。
繼承與非繼承屬性runtime fixture · read-only demo
驗收證據
勾選只是學習紀錄;真正完成仍要回到 Starter 的實際結果。
提示 1|方向
先分開查 color 和 border-top-width,不要只看整張卡。
提示 2|關鍵片段
父層有 4px border;子層只有在明確寫 border-width: inherit 後才應得到 4px。
提示 3|完整解答與原因
完整解答與原因:color 預設繼承,所以子層沿用父層顏色;border-width 預設不繼承,實驗切換明確 inherit 才由 0px 變 4px。