What happens if we try to apply the same id to multiple elements? Will our styles not get applied to the targeted, ided elements?


#1

Question

What happens if we try to apply the same id to multiple elements? Will our styles not get applied to the targeted, ided elements?

Answer

As HTML and CSS are designed to be very fault tolerant, most browsers will in fact apply the specified styles to all elements given the same id. However, this is considered bad practice as it defies the W3C spec.

Applying the same id to multiple elements is invalid HTML and should be avoided.


FAQ: Learn CSS Selectors Visual Rules - CSS Setup Selectors - ID Name
#3

For that purpose we have class attributes, which may be distrbuted everywhere and anywhere.

The reason we can only have one id is because it is a fragment identifier that can be hooked with an HREF.

<div id="history">

</div>

and anywhere else in the same page,

<a href="#history">History</a>

Imagine the confusion over which one to hook if there is more than one id="history". The browser may always go to the first one in the page, though I’ve not tested this. Best to stick to the spec and write valid HTML.


#4

Thank you very much for the reply @mtf! Very insightfull indeed.

Also in the next lesson it is explained another reason why not to use multiple “id”, which is because of the matter of Specificity of the elements. Using too many “id” can cause the document hard to edit in the future because it has a higher priority when CSS rules are applied. I hope I got it right, hehe.


#5

Specificity if something we should keep a tight rein on, keeping our document’s specificity as low as possible so that future changes to the page or site in general are not a massive undertaking, but a smooth transition.

style  id   class  type    # element
  0     0     0     1
  0     0     1     0
  0     1     0     0
  1     0     0     0

Higher specificity as we go left. The term priority is not really a common term in CSS. Specificity is an indication of importance of a selector.

p             element type
.class        element with class attribute
#id           element with id attribute
style         element with style attribute
!important    style property with !important override

specificity increases as we go down the list.