home ~ projects ~ socials

Make Nav Links From An Unordered List With Separators in CSS

Given this HTML

<nav>
  <ul>
    <li>alfa</li>
    <li>bravo</li>
    <li>charlie</li>
  </ul>
</nav>

You can use this CSS to create nav links that are all on one line with a | separator between them

nav > ul {
    list-style-type: none;
    padding-left: 0;
}

nav > ul > li {
    display: inline-block;
}

nav > ul > li:nth-last-child(n+2)::after {
    display: inline-block;
    content: '|';
    padding: 0 3px;
}

I like this approach because the :nth-last-child(n+2) puts the separator between the links without having to do anything in the HTML. And, it does so without adding one after the last link.

-- end of line --