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)