ehdv
ehdv

Reputation: 4603

Are there reasons not to use ARIA states and roles as selectors in CSS?

I'm currently working on making an accessible site using, among other things, ARIA tags. It occurred to me that attributes such as aria-invalid would be good selectors for my CSS to target, rather than using a .error class.

The benefit of this is leaner, more meaningful HTML, which is easier for me to hook into from CSS (and JS). That said, I haven't seen this done elsewhere so I'm suspicious there are downsides to leveraging accessibility tags for styling. I suspect the use of unconstrained attribute selectors makes for less performant CSS, but are there other downsides I haven't considered?

Upvotes: 20

Views: 7689

Answers (2)

tobib
tobib

Reputation: 2406

You need to understand that attributes like aria-invalid should be avoided in the first place. You should always use native semantics if available (e.g. required on input elements). This is called the first rule of ARIA.

I think what you really want is to add styling to computed ARIA states and properties. Unfortunately this is not supported in CSS at the moment.

In summary: There is nothing wrong with using [aria-invalid] as a CSS-selector. It will just not help you much because you should avoid that attribute in the first place.

Upvotes: 0

zzzzBov
zzzzBov

Reputation: 179176

Attribute selectors are a very flexible way to manage styles for large-scale CSS because the attribute selectors will always have a specificity of 0-0-1-0.

[aria-*] selectors are perfectly fine to use as styling hooks, and I also recommend using custom [data-*] attributes to fill in the gaps where you might need a one-off. Certainly class selectors should continue to be used, however you can do some very elegant style extensions with attribute selectors:

[data-foo] {
    color: red;
}
[data-foo="bar"] {
    color: blue;
}
[data-foo="fizz"] {
    color: green;
}

Each of these selectors has the same specificity, and the cascade will allow the styles to be applied appropriately.

You could create your own form of classes by using the [attr~="value"] selector if need be.

Using the "attribute contains" selector can be useful for a technique that I call "classy images"


One of the hidden benefits to using attributes over classes is a performance gain in JavaScript. Instead of having to check for the presence of a class on an element (which is remarkably easy to get wrong), browsers have supported getAttribute, hasAttribute, and setAttribute for a long time.

Upvotes: 20

Related Questions