Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shoud I prefer <nav><ul><li><a-or-other-tag> or <nav><a-or-other-tag>, from an accessibility standpoint? [duplicate]

Often, in books, tutorials, and some actual webpage, I see navigation bars marked up as <li>s elements in a <ul> element in a <nav> element, like this:

.site-nav {
  display: flex;
  justify-content: space-around;
  list-style-type: none;
  padding-left: 0;
}

.site-nav > li > a {
  border: 1px solid black;
  padding: 1em;
  text-decoration: none;
}

li { padding: 1em; } /* just for better appearance here on SO */
<nav>
  <ul class="site-nav">
    <li><a href="x">first</a></li>
    <li><a href="y">second</a></li>
    <li><a href="z">third</a></li>
  </ul>
</nav>

However, why shouldn't I prefer a solution like the following, where the <nav> contains directly all the contents of the <li>s from the example above?

.site-nav {
  display: flex;
  justify-content: space-around;
  list-style-type: none;
}

.site-nav > a {
  border: 1px solid black;
  padding: 1em;
  text-decoration: none;
}
<nav class="site-nav">
  <a href="x">first</a>
  <a href="y">second</a>
  <a href="z">third</a>
</nav>

One advantage I see is the lower specificity needed to target the <a> links (or whatever I'd put in their place, e.g. <button>s), but I still know too little about HTML to understand the implications of one or the other solution, especially as far as accessibility is concerned.

like image 434
Enlico Avatar asked Mar 01 '23 10:03

Enlico


1 Answers

The answer is straight forward, semantics and accessibility.

If I arrive at your second example without the <ul> with a screen reader then I have no idea how many links there are.

If I arrive at the first, correctly marked up example with a screen reader I will hear something similar to "navigation landmark, list of 3 items".

This lets me know that there are 3 links in the list so I can visualise where I am in the navigation as I move between them.

like image 124
Graham Ritchie Avatar answered Apr 06 '23 13:04

Graham Ritchie