Responsive Styling Using Attribute Selectors

Class-based atomic styling runs into a recurring problem: a declaration often needs a specific breakpoint for context. The usual fix is to prefix each class with the breakpoint it belongs to.

<div class="sm-span-12 md-span-6 lg-span-4"></div>

The approach holds up until the number of classes grows. At that point it gets hard to track which classes relate to one another, and where something should be added, removed or changed.

<div class="
  sm-span-12 
  md-span-6 
  lg-span-4 
  sm-font-size-xl 
  md-font-size-xl 
  lg-font-size-xl 
  md-font-weight-500 
  lg-font-weight-700">
</div>

Regrouping the classes can improve readability, and funky separators are also an option — invalid class names simply get ignored.

<div class="
  sm-span-12 
  sm-font-size-xl 


  md-span-6 
  md-font-size-xl 
  md-font-weight-500 


  lg-span-4 
  lg-font-size-xl 
  lg-font-weight-700">
</div>
<div class="
  [
   sm-span-12 
   sm-font-size-xl 
  ],[
   md-span-6 
   md-font-size-xl 
   md-font-weight-500 
  ],[
   lg-span-4 
   lg-font-size-xl 
   lg-font-weight-700
  ]">
</div>

Neither trick fixes the underlying mess. A cleaner alternative is to group attribute selectors instead of real classes, which avoids those implementation prefixes and gives a better overview.

<div 
 
 
 
>
</div>

These are not lists of classes but whitespace-separated lists of attributes, selected with [attribute~="value"]. The ~= operator only matches when the exact word appears in the attribute value.

@media (min-width: 0) {
 [data-sm~="span-1"] { /*...*/ }              
 [data-sm~="span-2"] { /*...*/ }   
 /* etc. */ 
}
@media (min-width: 30rem) {
 [data-md~="span-1"] { /*...*/ }   
 [data-md~="span-2"] { /*...*/ }   
 /* etc. */   
}
@media (min-width: 60rem) {
 [data-lg~="span-1"] { /*...*/ }   
 [data-lg~="span-2"] { /*...*/ }   
 /* etc. */   
}

The syntax looks a bit unusual, but translating atomic classes to attributes is fairly direct — .sm-span-1, for instance, becomes [data-sm~="span-1"]. Nothing is lost in specificity, since attribute selectors rank the same as classes. Attributes also let special characters like /+.:? be written without escaping.

The idea is not a proposal to abandon classes. It is simply meant to make switching declarations inside media queries easier to write, read and manage.