1

In example here: https://jsonformatter.org/html-validator/59ed54 I used ID "myHeader" three times:

<!DOCTYPE html>
<html>
<head>
<style>
/* Style the element with the id "myHeader" */
#myHeader {
  background-color: lightblue;
  color: green;
  padding: 40px;
  text-align: center;
}

/* Style all elements with the class name "city" */
.city {
  background-color: tomato;
  color: white;
  padding: 10px;
} 
</style>
</head>
<body>

<h2>Difference Between Class and ID</h2>
<p>A class name can be used by multiple HTML elements, while an id name must only be used by one HTML element within the page:</p>

<!-- An element with a unique id -->
<h1 id="myHeader">My Cities are cool</h1>

<!-- An element with a unique id -->
<h1 id="myHeader">My Citie are cool</h1>

<!-- An element with a unique id -->
<h2 id="myHeader">My Cities are cool</h2>

<!-- Multiple elements with same class -->
<h2 class="city">London</h2>
<p>London is the capital of England.</p>

<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>

<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>

</body>
</html>

The editor says it is valid HTML and works. Is this really an error or fine use?

3
  • use validator.w3.org/nu/#textarea to validate html Commented Feb 5, 2022 at 6:21
  • imgur.com/a/emLcaWH w3 validator says no Commented Feb 5, 2022 at 6:21
  • it works doesn't mean it's good. You won't face any issue in 80% of the cases but once you hit the remaining 20% you will suffer so don't do it Commented Feb 5, 2022 at 9:34

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Does it mean I can't use line <h1 id="myHeader">My Cities are cool</h1> again with same element or, line <h2 id="myHeader">My Cities are cool</h2> with different element or both?
1

Definitely bad practice. It's not causing any problem in static page and renders as valid but when you'll try to apply js or something to identify ids or work with dom then it'll be real problem.

q&a reference

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.