Sunday, 16 December 2018

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.




For example:






Or:







Or:




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?


Answer



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.



http://www.w3.org/TR/wai-aria/



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.



Delete


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

.






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 a valid use of the attribute unless a real role is not included. Browsers will apply the first recognized role in the token list.



...



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.)


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...