How to Use Div and Span in an Accessible Way

Using divs or spans is not a bad action per se, but when used incorrectly, they can create problems for assistive technologies to understand a website. I’ll share some common misunderstandings and how to avoid them.

The main problems with these elements are:

  • They lack semantics, and because of that, assistive technologies cannot assign to them a role or behaviour by default.
  • They do not structure content, unlike landmark elements like navbar, main, or footer that can order the navigation.

What this means is that while we can make a div look like a button or a card, using CSS, it still does not have a semantic meaning. Assistive technologies will likely ignore it, forcing us to find other solutions. Let’s see how to get to the same result with a semantic element versus a div. A button on HTML would look something like this:

<button name="button">
  Click Me!
</button>

That piece of code will automatically look like this:

In the meantime, a div with the same text would be:

<div>
  Click Me!
</div>

And in the browser it would be:

So, why make things more complicated when we can just use the correct semantic tag from the start?

Using Them Wisely

2 scenarios allow us to use divs and spans in a way that really helps to deliver the best experience:

  1. To give visual attributes with CSS styles. Divs will be helpful to generate a block of content, while a span will allow us to group inline elements. To name a case, in a form, we could use divs to group labels and inputs and give them styles, and the screen reader will ignore the div’s attributes.
  2. To build custom components. In these advanced cases, we must also include the appropriate ARIA roles and attributes so assistive technologies can understand them and communicate them correctly. Following the example, we can always create a div with the necessary attributes to have the same properties (visual styles, ARIA attributes for assistive technologies, and the corresponding JavaScript to assign them the corresponding behaviour).

Building an accessible web is key to ensuring that as many people as possible can access our content.