Using ‘aria-labelledby’ as a styling hook

A couple of months ago, I was greatly inspired by an article on Smashing Magazine entitled Semantic CSS With Intelligent Selectors by Heydon Pickering. It goes into depth on how aria roles can be used as hooks for button styling among other things.

After using some of Heydon’s techniques, I got thinking about how they could be applied to layouts and suchlike. I harassed him on Twitter for his thoughts styling various elements with landmark roles and then stumbled on the aria-labelledby attribute. It turns out that this makes for a perfectly semantic styling hook.

Normally I would use classes when styling sections of content for example:


<section class="section-latest-products">
  <h2>Latest products</h2>
  <ul>
    ...
  </ul>
</section>

<section class="section-press-news">
  <h2>Press news</h2>
  <ul>
    ...
  </ul>
</section>

Now using ‘aria-labelledby':


<section aria-labelledby="latest-products">
  <h2 id="latest-products">Latest products</h2>
  <ul>
    ...
  </ul>
</section>

<section aria-labelledby="press-news">
  <h2 id="press-news">Press news</h2>
  <ul>
    ...
  </ul>
</section>

And the CSS:


section[aria-labelledby="latest-products"] {
  /* Latest products styling */
}
 
section[aria-labelledby="press-news"] {
  /* Press news styling */
}

Using ‘aria-labelledby’ not only increases accessibility, it gives us a styling hook with the bonus of being able to link to the relevant sections using anchors such as ‘#press-news’.

Having not been fan of techniques such as BEM due to them littering markup with unsemantic class names, this just feels right. I’m sure there are other ways that aria attributes could also be used.

Thanks again to Haydon and his article for opening a can of worms in my head, which lead to this solution.

See the Gist and the Twitter conversation.