DEV Community

Cover image for What Happens When Two IDs Clash? (And Why Your CSS Still Breaks)
Pawar Shivam
Pawar Shivam

Posted on

What Happens When Two IDs Clash? (And Why Your CSS Still Breaks)

=> Two Same IDs? Big Problem 🚨

You write:

<div id="box">First</div>
<div id="box">Second</div>
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ This is INVALID HTML

IDs must be unique.


=> But What Actually Happens?

Browser doesn’t crash πŸ˜„

πŸ‘‰ It still renders both
πŸ‘‰ But behavior becomes unpredictable


=> CSS with Same ID

#box {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ BOTH elements become red

Even though it’s wrong ❌


=> JavaScript Problem (Hidden Bug)

document.getElementById('box')
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Only returns FIRST element

Second one ignored ❌


=> Now Let’s Make It Complex πŸ”₯

<div id="box" style="color: green;">First</div>
<div id="box">Second</div>
Enter fullscreen mode Exit fullscreen mode
#box {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ First = green (inline wins)
πŸ‘‰ Second = red


=> Add !important

#box {
  color: red !important;
}
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Now BOTH become red

Even inline gets overridden 😳


=> What If Same ID in Multiple CSS Files?

<link href="a.css">
<link href="b.css">
Enter fullscreen mode Exit fullscreen mode

a.css:

#box { color: blue; }
Enter fullscreen mode Exit fullscreen mode

b.css:

#box { color: red; }
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Result: red

πŸ‘‰ Last loaded file wins


=> Same Specificity Inside Same File

#box { color: blue; }
#box { color: red; }
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Bottom rule wins


=> Why This Is Dangerous

β€’ Unpredictable behavior
β€’ JS bugs
β€’ Hard debugging
β€’ Breaks accessibility


=> Real Dev Rule

πŸ‘‰ ID = UNIQUE

Always.


=> Better Approach

Use classes:

<div class="box"></div>
<div class="box"></div>
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Safe + scalable


=> Pro Insight

Specificity is NOT the only factor

Final winner depends on:

πŸ‘‰ Specificity
πŸ‘‰ Source order
πŸ‘‰ Inline styles
πŸ‘‰ !important


=> Final Thought

Browser tries to fix your mistakes…

πŸ‘‰ But your code becomes harder to control


=> What Do You Think?

Have you ever debugged a bug caused by duplicate IDs?

Top comments (0)