Ditch Your Stateful CSS Classes for an Accessible Web

It’s easy to brush tasks under the rug in the name of efficiency or time. Daniel shares an easy way to start incorporating accessibility into your coding life by examining stateful CSS classes.

In recent articles, we talked about the importance of aria labels. If you haven’t read them yet, go check out part one on aria-labels and part two on aria-hidden to give yourself a little refresher on accessibility and a quick introduction into aria labels and what they do.

Time to Be Practical

Honestly, I still find it difficult to remember to build with accessibility in mind. It isn’t that I don’t want to; it is just never on the top of my priority list. First, that’s an awful, unacceptable thing. Second, that’s still an awful, unacceptable mindset. All I am doing is perpetuating a real problem and not actively looking for ways to help solve it.

Instead of continuing to feign ignorance, I have begun to add little practical pieces into my everyday development. If you are like me and need to start adding in little things to help kick start your way toward accessibility, here is my first tip:

Stop using stateful CSS classes.

Wait, What?

As we have all heard before, naming CSS stuff is really hard. It is difficult to create CSS classes that are descriptive and helpful. So, as an alternative to using time coming up with class names for styles, don’t. Instead use aria labels!

But what about my styles?! Don’t worry, CSS can target aria labels without a hitch. For instance, if you need to add a visibility: hidden for an element containing aria-hidden=”true” just add it like so:

[aria-hidden="true"] { visibility: hidden; }

Similar to CSS, toggling aria labels with JS is just as easy. Even though there may not be a toggleLabel() function, it is just as easy to replace the value of an aria label with jQuery, your favorite JS library, or native JavaScript.

Here are two quick basic—and I mean really basic—navigation examples. The first uses a state class of .is-hidden to toggle the menu while the second uses just aria labels.

Traditional Stateful Classes Example on Codepen

Aria labels Example on Codepen

As you can see, the code is not much different, and you can start to see how you can start to refactor any current code you have with aria labels!

Shiny New Hammer

Hopefully this gives you something small, but significant you can add to your everyday development. Remember, it is better to start doing something than paralyze yourself with content and do nothing. That being said, get rid of those stateful classes and refactor it for a better, more accessible web!