designsystemet icon indicating copy to clipboard operation
designsystemet copied to clipboard

Use data attributes for css

Open Barsnes opened this issue 9 months ago • 7 comments

This is a suggestion, and needs to be investigated

Today we have explicit classes for sizes, etc. - but it would be nice if we can have a good developer API for this, even if our users use just CSS classes.

A proposal is to use data attributes like we use props in react, so things like size and variant are the same across all components. This is also how we will do theming, so it plays nicely with that,

Given a button we want to be small. secondary variant and danger color, we would do this:

<button class="fds-btn" data-size="sm" data-variant="secondary" data-color="danger">
button
</button>

Our css would look like this:

.fds-btn { ... }
.fds-btn[data-size="sm"] { ... }
.fds-btn[data-variant="secondary"] { ... }
.fds-btn[data-color="danger"] { ... }

A big plus for doing this is that our users only need to set one class to define the component. It is easy to select, and change a data attribute with javascript, easier than classes:

let value = el.getAttribute("data-size");
el.setAttribute("data-state", "sm");

CSS Trick has a great article about this

Barsnes avatar May 23 '24 07:05 Barsnes