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.

One thought on “Using ‘aria-labelledby’ as a styling hook”

  1. “…and then stumbled on the aria-labelledby attribute.”

    It would make sense to include a quick explanation of what the purpose of this attribute is (as a follow up sentence), as a preventive measure for people who won’t click on the link or might be turned off by the W3C spec (which sometimes aren’t easy to digest and can therefore appear intimidating). (Also, W3C specs tend to rename their fragment identifiers occasionally which could render your link less useful.)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>