Eliter
Eliter

Reputation: 163

Can you use the same ID with different element types in CSS?

I know this is invalid HTML:

<p id="sally">paragraph</p>
<p id="sally">paragraph</p>

Is this also invalid?

<div id="sally">
  <p id="sally">sally paragraph, inside of sally div</p>
  <p>paragraph with nothing special.</p>
</div>

and something like

div.#sally{
  width: 90%;
  height: 3em;
  padding: 20px;
}
p.#sally{
  font-size: 1em;
  color: red;
}

Upvotes: 2

Views: 1641

Answers (3)

Nicolas Dilley
Nicolas Dilley

Reputation: 26

No, it won't work because that is the purpose of ID--to be unique in the document. They made classes available so you can use the same style several times.

Upvotes: 1

Quentin
Quentin

Reputation: 943157

I know this is invalid HTML

Correct

Is this also invalid?

Yes. An ID must be unique in the document. Not unique per type in the document.

(That won't stop browser error recovery from sometimes giving you the result you are trying to achieve, but you should not depend on that).

and something like

You can't use .#. A . starts a class selector. A # starts an ID selector.

You can have

div#sally { ... }
p#sally { ... }

And then have two different documents, one with a div with that ID and one with a paragraph with that ID, but both of which <link> to the same stylesheet.

If you want to identify two things are being in a group, then use a class. That is what class is for.

Upvotes: 1

StardustGogeta
StardustGogeta

Reputation: 3406

div#a {
  background-color: red;
}

span#a {
  background-color: lightblue;
}
<div id="a">Hello</div>
<span id="a">world</span>

I do not at all recommend this, as classes are a much better way of handling things. However, as a proof of a concept, this can indeed be done with CSS.

Upvotes: 0

Related Questions