3 ms·
Wow I like this solution a lot, and I’m sad that it’s presented after a million paragraphs of ranting and a terrible title. The tl;dr is: if you use custom ele
by skrebbel 2y ago
Wow I like this solution a lot, and I’m sad that it’s presented after a million paragraphs of ranting and a terrible title.
The tl;dr is: if you use custom element names (instead of “.Card”) and attributes (instead of “.Card—size-big”), things get very clear and you lose many downsides of other approaches (such as name clashes and unmaintainable soup):
So write HTML like this:
<my-card data-size="big"></my-card>
And CSS like this:
my-card { /* ... */ }
my-card[data-size=big] { width: 100%; }
my-card[data-size=medium] { width: 50%; }
my-card[data-size=small] { width: 25%; }
Personally I think this idea is really great. I’m not sure yet that I prefer it over Tailwind in all situations, but it seems obviously better than eg BEM, CSS Modules, inline styles, styled-components and all those other approaches. I really love the idea, it feels like a “woa why didn’t I realize this before” kind of thing.
EDIT: Thinking on this a bit, I’m not sure I’d replace every single div with a custom element like the author suggests, I think a div-with-a-class works just as well and is easier to grok for other readers of the code cause everybody knows how a div works. Readers don’t have to figure out whether it’s a defined custom element (ie a JS class) or just a CSS level thing, etc.
But the idea of using attributes instead of .my-thing—-level-3 is genius in my book. It means you only ever need one class per element at most. No more concatenating long className props, no more repetitive prefixing, it’s scoped by definition, etc. Also all the logic in the HTML rendering code is nicely siloed:
<div
className="my-thing"
data-level={someFunc(props.foo)}
data-size={props.size ?? "big"}
etc
>
So much nicer than some nested classname object hack!
- vbezhenar 2y agoI'm out of touch, I guess. Can I just use any tags with ordinary HTML? Is it correct HTML?
- debugnik 2y agoYou can use any tag name with a hyphen, IIRC.
- fhd2 2y agoYes, though I personally don't use it, a weird fear of colliding with obscure existing or new tags down the line. But technically, name spacing them with a prefix should cover that.
- skrebbel 2y agoYep. The standard promises that new standard tags will never contain a dash, so if your custom tag does contain a dash, it can’t ever clash with future new browser features.
- beardyw 2y agoThe "data" prefix, followed by whatever you want, has been formalised for quite some time. The DOM provides a "dataset" property.
- matheusmoreira 2y agoI didn't know I could just create my own tags in HTML. I assume this makes it harder for accessibility technologies to understand the page?
- xigoi 2y agoObviously if there is a semantic tag, you should use it. But if not, a custom tag is not worse than a <div>.