Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write article about using data attributes for styling #2785

Open
mimarz opened this issue Nov 15, 2024 · 0 comments
Open

Write article about using data attributes for styling #2785

mimarz opened this issue Nov 15, 2024 · 0 comments

Comments

@mimarz
Copy link
Collaborator

mimarz commented Nov 15, 2024

We got a question on slack about our reasoning for using data attributes for styling. https://designsystemet.slack.com/archives/C05RF86A3K7/p1731598129711029

Lets make a blog post about us using data attributes for styling.

Notes

  • CSS nesting is Baseline 2023, so its widely supported on modern browsers, but we still transpile it to full classes for dist 🙂
  • Browsers are much better at data-attributes selectors now so performance is negligible compared to classes.
  • Better legibility using data-attributes compared to long list of classes. We noticed pretty quick that using classes for all different modifiers and composing with other styles didn't quite scale and was cumbersome to sift through for end users.
  • Avoid conflicting states and clearer indication of related prop values, ie data-size="sm | md | lg"
  • You can add types to data-attributes for both typescript and your IDE for (plain html). We also plan to auto-generate some of these based on your theme for typescript as an opt-in help 🙂
  • Easier to toggle styling with data attributes instead of string concatenating class names.
  • Elements have also a more similar use to components, so this will make it more familiar whichever component library you are using and lines up nice with potential web-components in the future
  • When toggling strings in classNames, you need to know both previous an next state of a component: button.classList.remove('button--sm'); button.classList.add('button-lg')
  • BEM-selectors was a nice way to keep CSS specificity down, as .table > th is stronger than .table__th . This is no longer needed though as we can utilize CSS layers, and depend on the DOM structure guaranteed by the HTML standard anyway ☺️

Short example for a button

Traditional BEM:

<button 
 class="ds-btn ds-btn--md ds-btn--primary ds-btn--accent">
 Knapp
</button>

Data attributes:

<button
 class="ds-button" 
 data-color="accent" 
 data-variant="primary"
 data-size="md">
Knapp
</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: 📋 Backlog
Development

No branches or pull requests

1 participant