0

I was reading about the difference between ID and class selectors where it says

"Each page can have only one element with that ID"

Though, How the #one managed to select both HTML elements.

#one {
  color: blue;
}
<div>
  <p id="one"> blue</p>
  <h1 id="one"> H1</h1>
</div>

Result run on chrome browser: both elements are displayed with blue color .

j08691
  • 204,283
  • 31
  • 260
  • 272
Omar Hamed
  • 41
  • 1
  • 5
  • 3
    It's invalid HTML regardless – j08691 Oct 03 '19 at 17:33
  • From [the spec](https://drafts.csswg.org/selectors/#id-selectors): _“An ID selector represents an element instance that has an identifier that matches the identifier in the ID selector. (It is possible in non-conforming documents for multiple elements to match a single ID selector.)”_. – Sebastian Simon Oct 03 '19 at 17:34
  • you need to change `id` to `class` to be a valid HTML. – Gildas.Tambo Oct 03 '19 at 17:34
  • 1
    CSS will still apply styling to elements with the same `id`, however, as j08691 pointed out, it's invalid HTML. – disinfor Oct 03 '19 at 17:35
  • @Gildas.Tambo That’s not the question. – Sebastian Simon Oct 03 '19 at 17:35
  • @SebastianSimon is it mentioning a specific scenarios where it will be working ? – Omar Hamed Oct 03 '19 at 17:41
  • 2
    @disinfor The question is not asking whether duplicate IDs are valid. The question is asking why CSS applies styles to an invalid document. – Sebastian Simon Oct 03 '19 at 17:42
  • 1
    @SebastianSimon yeah, I read the question. Look at my response. CSS will be applied regardless if the HTML is invalid - because CSS doesn't care about HTML validity..it's simply searching for matching selectors. – disinfor Oct 03 '19 at 17:44
  • I think also the css style will be cheaper/easier to render without checking if the html is valid ;) – Julian Oct 03 '19 at 23:50

1 Answers1

-3

In HTML, each id has to be unique, while various elements can have the same class.

CSS that starts with a tag apply to all the tags in your HTML code. p {color: red;} means all paragraphs will be red.

CSS that starts with the id tag apply to all the ids. #one {color: red;} means both lines will be red.

CSS that starts with the class tag apply to all elements of a class. .test {color: red;} means only elements with the class 'test' will be red. Example:

<div>
  <p id="one" class='test1'> blue</p>
  <h1 id="two" class='test2'> H1</h1>
</div>

And your css looks like:

.test1 {color: blue;}
.test2 {color: green;}

Blue will be blue, and H1 will be green.

  • 3
    OP asks "why" it works, despite invalid syntax, and your answer doesn't explain that. – Asons Oct 03 '19 at 17:46