Hacker News new | past | comments | ask | show | jobs | submit login

I don't understand how "<div class="Card" data-size="big"></div>" is better than just <div class="Card big">, then using a .card.big selector?

The article just says "but this can cause specificity issues, which can create problems further down the line" to move the same thing into attributes rather than just use the thing for what it was designed for there has to be a good reason.




They key difference is that an attribute can only appear once on an element, and consequently only have one of its variants present. Classes can present multiple variants at once.

At a surface level `<div class="Card" data-size="big">` isn't really any better `<div class="Card big">`. But `<div class="Card" data-size="big" data-size="small">` is not valid HTML - the second attribute is discarded. While `<div class="Card big small">` has no such contract, and as such is valid HTML and the CSS is unlikely to account for it, perhaps doing surprising things.


This is what BEM solves. You do not have class="Card big" but class="Card Card_big". And if you care about modifier conflicts you may always define a rule .Card_big.Card_small { /* whatever makes sense */ } and not rely on a random application of attributes.


It's not and that's the reason why the author doesn't address it in their article. It's just bad faith.

Especially with CSS pre-processors (because they make writing that syntax in the CSS file super easy) which basically everyone is using, ".card.card-big" is the obviously right solution.

It is easy to read, specific, doesn't risk collisions, doesn't risk adding broken styles if you forgot the "card" class on the element, etc. It addresses all the negatives outlined in the "BEM is not the solution" section of the article.

The only "argument" that still sticks against this one is that "it's verbose", but not once in my career have I seen a __good__ software engineer discard a perfect solution because "it's verbose".


As this article argues, problem with CSS Classes is that a CSS Class can be applied to _any_ element where custom properties will be scoped to the elements that the CSS was meant to be used for.


Custom properties can be applied to any element as well. You can constrain the effects of either to only the elements they should affect in your CSS rules.


> Custom properties can be applied to any element as well.

Well, no, they can't. That's the point the article is making.

Classes can compose arbitrarily, i.e. class="size-small size-big"

Whereas data-size="small big", while valid syntax, would not be styled by a rule targeting elem[data-size="small"]


JSX is the answer: "<Card big />"




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: