0

Mozilla Developer Network states in their CSS tutorial -

"you can only have one element with each unique ID on a page, but many elements within the same class".

I must not be understanding that correctly.

I interpret that statement in the following way:

  • Within an HTML document, styled with a .css file, you can assign a styling to a Unique Identifier (ID).
  • You can apply that styling to only one element within your page.
  • Any subsequent uses of the ID will fail, or perhaps only the last application will be applied to the page.

However, in practice, I am able to apply an ID to as many elements as I want. As an example, I applied the ID to two <p> elements and one <div> element, and all of the those elements had the styling attached to that ID applied to them.

How am I meant to interpret that statement at the beginning of my post?

Is that more of a "best practices" type thing or are there hard rules within HTML and CSS that I am misunderstanding?

Example code. The top section is the output. The middle section is the CSS code. The bottom section is the HTML code

With my interpretation, only one of those elements should be styled by the ID, but all three are receiving the styling.

j08691
  • 204,283
  • 31
  • 260
  • 272
Slappy
  • 1
  • 1
  • 1
    All it's saying is that each ID on a page must be unique and cannot be reused on the page. Any element can have it's own, unique ID. Classes on the other hand, can be gives to multiple elements. Two divs can have the same class, but they can't have the same ID – j08691 Feb 20 '23 at 17:38
  • 1
    The browser is very forgiving. You can also write html without an ``, ``, ``, or ` ` and the browser will try to do the best it can. However if you write invalid html their are a bunch of downsides, like cross browser inconsistency, bad SEO, and as you said not following best practices. If you don't follow the specification then you don't get any guarantees about what will happen. – Zachiah Feb 20 '23 at 17:40

0 Answers0