Hacker News new | ask | show | jobs
by SkeuomorphicBee 820 days ago
>Use attribute selectors to convey unicity.

> /* Do */

> [id="main"] { max-width: 80ch; }

> /* Don't */

> #main { Max-width: 80ch; }

I strongly disagree with this kind of guideline. The id attribute has very good uses, and in those cases the hash syntax should be the preferred way.

The use of id in an attribute selector is such a bad choice that makes me question the whole document.

1 comments

I'm curious: why is it such a bad choice?

As for the #selector, in what cases do you need that much specificity? Not a rhetorical question!

iirc, ids are indexed - that is, when you select an #id, the engine picks the element directly out of the DOM. It’s the fastest / most performant way to select an element, because it has the smallest pool of possible nodes to evaluate to match the id provided.

If you use an attribute selector, the engine must search through every single node in the DOM in order to return matches - an incredibly costly operation by comparison.

(Disclaimer, there may well be optimizations I’m not aware of at this point, but I’m pretty sure that’s why ids are generally preferred as a rule of thumb)

I think these rules (and I think they are excellent) are poorly named as "efficient" css. That makes me think of performance.

In that case, yes it's less performant. But the specificity problem is so significant that I've followed the rule of never using ids for styling at all. The problems I've run into with CSS have entirely been regarding maintainability and preventing visual bugs, I've never had any CSS performance problem worth addressing. (I almost skipped this submission because I thought that was what is about, I'm glad I didn't.)

True, this change is about maintainability.

I'm sure the browser css engine treats that id attribute selector (without any regex-like) as an #id. Now if it were [id(*|^|$)=''] then it could have performance consequences, but they won't show up until you have thousands upon thousands of elements at which point maybe you should've looked into virtualization yesterday and not jump to wildcard selectors (speaking from experience).

I see, yes. I meant "efficient" in it's pure economic definition:

Producing effectively with a minimum of waste, expense, or unnecessary effort.

Is there a better term you're thinking of?

And in my experience, the performance cost of using attribute instead of id selectors is so small as being imperceptible. So, as you say, the gain of suing them far outweighs the possible cost.

Yeah, I know about that. Still, a good point. Thanks.

Nevertheless, in practice, I haven't seen any perceptible performance cost in using attribute selectors. It may have been the case years ago, when browsers weren't as efficient or devices as powerful.

I'd say the reduction of specificity here is well worth the theoretical cost.