5

Is it O.K. to use the same name for a classname and an ID name? Is it a code smell?

<div class="wrapper" id="wrapper"></div>
user2952265
  • 1,590
  • 7
  • 21
  • 32

6 Answers6

11

Yes, it's valid to do it. It's not common to need to do it, though: it's a bit of a code smell. It may indicate you need to revisit your naming conventions.

To expand on the issue of naming conventions and semantics:

When you use an ID of wrapper, you're saying "This is the wrapper - the only one of its kind". When you use a class of wrapper you're saying "This is one of the wrappers, and there may be others like it". Saying both of those things at the same time is a bit weird, right?

I'd suggest that you use a specific ID: #primaryWrapper, #outerWrapper, etc. That means you're expressing 'primaryWrapper is one of the wrappers', which makes heaps more sense.

Ben Hull
  • 7,524
  • 3
  • 36
  • 56
6

Yes, it's totally valid and you can do it

Hopefully you know that
#ID must be unique-per-page, while
.CLASS can be assignet to more than one element.

If you incline to write clean and readable HTML markup, try always to keep your attributes at an understandable minimum.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
3

Yes you could, but as a general rule you shouldn't. Classes can be reused, but IDs ned to remain unique. Try wrapper1 an wrapper2 if you need to.

  • 1
    I'd say that wrapper1 (as an ID) and wrapper2 (as a class) would be even less useful than wrapper as both ID and class: the 1 and 2 seem to indicate that the two are siblings/equals, which isn't the case. – Ben Hull Jan 14 '14 at 00:14
  • 1
    I suppose in some instances one would confuse this...especially if they are using the same name for an id and a class... – user3192241 Jan 14 '14 at 00:16
3

Yes it is OK, from the broswers' percpective they are two completely different elements.

The classes are defined using . and IDs are defined using #.

But be careful to not confuse yourself when coding.

For more info you can refer to the documentation of
Element identifiers: the id and class attributes at
http://www.w3.org/TR/html401/struct/global.html#h-7.5.2

Arbel
  • 30,599
  • 2
  • 28
  • 29
2

Yes, they are different entities. However, it is not OK to use the same ID on multiple entities.

JerryHuang.me
  • 1,790
  • 1
  • 11
  • 21
0

Yeah, you are OK.

As people stated, just remember that you keep the id unique.

POINTER:

classes are usually used to group many things that would be styled the same or very similarly.

id's are used to identify a specific element, mainly for javascript.

elliotanderson
  • 442
  • 4
  • 14
  • The distinction that classes are mainly used for styling and IDs for Javascript isn't true, and it's not even a reliable convention - some people might use them that way, but just as many don't. This question can be answered without reference to CSS or Javascript. – Ben Hull May 26 '20 at 07:23