jeroen jeroen - 8 months ago 28
HTML Question

What is the purpose of the "role" attribute in html?

I keep seeing role attributes in some people's work. I use it too, but I'm not sure about its effect.


<header id="header" role="banner">
header stuff in here


<section id="facebook" role="contentinfo">
facebook stuff in here


<section id="main" role="main">
main content stuff in here

Is this role attribute necessary?

Is this attribute better for semantics?

Does it improve SEO?

A list of roles can be found here, but I see some people make up their own. Is that allowed or a correct use of the role attribute?

Any thoughts on this?


Most of the roles you see were defined as part of ARIA 1.0, and then later incorporated into HTML5. Some of the new HTML5 elements (dialog, main, etc.) are even based on the original ARIA roles.

There are two primary reasons to use roles in addition to your native semantic element.

Reason #1. Overriding the role where no host language element is appropriate or, for various reasons, a less semantically appropriate element was used.

In this example, a link was used, even though the resulting functionality is more button-like than a navigation link.

<a href="#" role="button" aria-label="Delete item 1">Delete</a>

Screen readers will hear this as a button (as opposed to a link), and you can use a CSS attribute selector to avoid class-itis and div-itis.

*[role="button"] {
  /* style these a buttons w/o relying on a .button class */

Reason #2. Backing up a native element's role, to support browsers that implemented the ARIA role but haven't yet implemented the native element's role.

For example, the "main" role has been supported in browsers for many years, but it's a relatively recent addition to HTML5, so many browsers don't yet support the semantic for <main>.

<main role="main">…</main>

This is technically redundant, but helps some users and doesn't harm any. In a few years, this technique will likely become unnecessary.

You also wrote:

I see some people make up their own. Is that allowed or a correct use of the role attribute?

That's not an invalid use of the attribute unless a real role is not included. Browsers will apply the first recognized role in the token list.

<span role="foo link note bar">...</a>

Out of the list, only link and note are valid roles, and so the link role will be applied because it comes first. If you use custom roles, make sure they don't conflict with any defined role in ARIA or the host language you're using (HTML, SVG, MathML, etc.)