今日已更新 80 条资讯 | 累计 20052 条内容
关于我们

🚨 CSS Specificity — The Hidden Reason Your UI Breaks

Fazal Mansuri 2026年06月06日 14:57 5 次阅读 来源:Dev.to

Most developers learn CSS specificity once. They remember: #id > .class > div Then move on. Until one day… Everything looks correct. The CSS is present. The selector is correct. The z-index looks higher. And yet the UI is broken. That’s when CSS specificity stops being a beginner topic and becomes a production debugging problem. The Production Incident That Started This Recently, I was working on a microfrontend application. Everything worked fine initially. I opened a page, launched a modal and the UI looked correct. Then I navigated to another microfrontend. Its CSS got loaded. After returning to the original microfrontend, suddenly: ❌ Modal appeared behind page content ❌ Overlay behaved incorrectly ❌ z-index looked correct but wasn't working DevTools showed my CSS rule still existed. Yet another CSS rule was winning. The culprit? CSS Specificity. 🧠 What is CSS Specificity? CSS specificity is the algorithm browsers use to decide: Which CSS rule wins when multiple rules target the same element. Browsers don't simply apply: "The last CSS rule." That's one of the biggest misconceptions. Specificity is calculated first. Only when specificity is equal does source order become important. ⚔️ Example .modal { z-index : 9999 ; } .some-library .modal { z-index : 100 ; } HTML: <div class= "some-library" > <div class= "modal" ></div> </div> Many developers expect: .modal to win because the value is larger. But CSS doesn't compare values first. It compares selectors. 🧮 How Specificity Works Specificity is usually represented as: ID - CLASS - TYPE Specificity Table Selector Specificity * 0-0-0 div 0-0-1 .modal 0-1-0 [type="text"] 0-1-0 :hover 0-1-0 #dialog 1-0-0 Inline Style Highest MDN defines specificity as the weight browsers calculate to determine which declaration gets applied when multiple selectors match the same element. Example Calculation Selector: button .primary Contains: button → 0 -0-1 .primary → 0 -1-0 Total: 0-1-1 Another selector: #header button .primary Contai

本文内容来源于互联网,版权归原作者所有
查看原文