Luca Rossi
Luca Rossi

Reputation: 409

CSS selector conventions: Why does Chrome suggest you to select via #id when possible?

Example: I have this element:

<div id="foo" class="my-foo"></div>

If I click the "+" button in the chrome console chrome_btn

Chrome will "suggest" to select the div via it's id, and not via class, like this:

div#foo{}

Isn't kind of incorrect to style elements via their IDs?

Upvotes: 1

Views: 158

Answers (1)

BoltClock
BoltClock

Reputation: 723668

When adding a style rule for an element with an ID, the inspector generally assumes you want to style only that element, and not any other div elements or elements that happen to match .my-foo, hence the suggestion of an ID selector.

It's not clear to me why it prepends a type selector to the ID, though. If it's trying to guard against duplicate IDs, it's certainly not going to prevent the selector from matching two divs with the same ID, which is far more likely than two elements of different types having the same ID.

Upvotes: 2

Related Questions