0

I was teaching my sister how to do CSS and encounter this weird issue - ID behaves like a class. In my HTML, there are two elements sharing the same id. I was expecting that the first element containing that id will be the one who gets styled, the second element containing that id should not be styled right?

<!DOCTYPE html>
<html>
<head>
    <title>ID test</title>

    <style>
        #id1{
            color: blue;
        }
    </style>
</head>
<body>
    <div id="id1">text1</div>
    <div id="id1">text2</div>
</body>
</html>



But this is the result. Both of them gets styled with the text color blue:

enter image description here

Lou
  • 83
  • 1
  • 7
  • Having more than one id is simply a "bad practice," and classes should be used instead. Having more than one id on an element can make the page confusing, and sometimes does not work on other browsers. Classes can also have subclasses, so your sister should use those instead. – Stick-Figure Dec 29 '20 at 16:22
  • 1
    It's more than bad practice. It's invalid. An ID that isn't unique doesn't ID anything. JavaScript won't behave like this--you'll see single elements affected and not all of them. – isherwood Dec 29 '20 at 16:25
  • [This question already has answers here](https://stackoverflow.com/questions/7262195/several-elements-with-the-same-id-responding-to-one-css-id-selector) Check Here – Ali Mirza Dec 29 '20 at 16:26
  • Yeah I know it's bad practice. My sister was asking the difference between id and class, so I explained it to her that class for multiple elements and id for a single element. And I tried to convince her with a result that she can see, however, that what happened, that's why I asked. – Lou Dec 29 '20 at 16:53

2 Answers2

2

ID values are supposed to be unique and things like document.getElementById wouldn't work anymore. This is from https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id

Timothy Chen
  • 431
  • 3
  • 8
1

Although ID's should be unique and used once on a page, they will still share the styling if used multiple times.

Bjorn.B
  • 1,473
  • 1
  • 10
  • 11