CSS & Projects

Projects, Scrum, Trello & Code

CSS Without Classes : The Attributes Module

Yesterday, Glenn Maddern introduced a new concept for styling HTML websites : the Attributes Modules. His explanation being very thorough and well-written, you should read it first.

I used it today for a small pen about language learning card :

The HTML uses attributes (starting with am-attribute so I know it’s part of this module, it’s very much like Angular’s ng-stuff) instead of classes.

The code :

Here I have three modules :

  • Card : am-Card to style Cards in general
  • Lang : am-Lang to make sure the user can recognize pinyin (latin-characters chinese) at a glance for example.
  • Question : am-Question, which will hide and show blocks of text, so the user has to guess them.

The HTML template for my Card :

1
2
3
4
5
<article am-Card>
  <p am-Lang="chinese"><em am-Question="hidden"></em>一个铁剑。</p>
  <p am-Lang="pinyin"><em am-Question="hidden"></em> yī ge tiě jiàn.</p>
  <p am-Lang="english">I <em am-Question="none">sculpt</em> one iron sword</p>
</article>

The CSS I use :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* CARD module */
[am-Card] {
  /* Basic CSS stuff about Cards*/
}

/* QUESTION module */
/* stuff about Questions that won't change if I apply a modifier */
[am-Question] {
  font-style: inherit;
  border-radius: 0.1em;
}
/* Questions with "shown" state will have a sliiight background color
   to know it's been revealed */
[am-Question~="shown"] {
  background-color: rgba($color-hidden, 0.3);
  transition: all 0.1s ease-in-out;
}
/* Questions with "hidden" state will have the same background-color
   and color to hide them ! I'm quoite proud of this trick :P */
[am-Question~="hidden"] {
  color: $color-hidden;
  background-color: $color-hidden;
}

Pro’s and Con’s

  • You never have to worry about two .hiddenclasses with different behaviors.
  • You won’t have huge Card__Question--hidden classes like BEM does, because each module has its own attribute (avoids Global Namespace !).
  • Since all your attributes have meaning, I think we can use the same attributes for CSS and JS. The attribute only shows an information, CSS and JS can do whatever they want afterwards.
  • But it’s not very pretty to have [am-Question~="shown"] everywhere in your css…

The full Pen :

See the Pen Hide some text by Pierre (@Marekje) on CodePen.