No Time Dad

A blog about web development written by a busy dad

Creating a ul li Horizontal Display

Changing an ui li vertical display to a ul li horizontal display turned out to be easier than I thought. The best solution was flexbox. By simply initializing a flexbox container in the parent ul element, the child li will be displayed horizontally instead of vertically. No further code changes required. And I get the added benefit of having my ul element now a flexbox container.

ul {
  display: flex;
}
<ul>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ul>

Which looks something like this:

  • item 1
  • item 2
  • item 3

Compared to the default behavior:

  • item 1
  • item 2
  • item 3

Why would you want to change to a ul li horizontal display? The most common use case is for navigation links. Especially those in a top toolbar. Yes, you could just use standard div elements, but I think that sticking to semantic html is always a good idea. The exact reason that ul and li tags exist is for creating lists.

There’s a second, slightly older, but still very valid approach for creating a ul li horizontal display that’s worth mentioning. And that is using display: inline; on each li element. The main drawback here is that if you were using css modules you’d need to add a class to each element. Otherwise you can create the structure css ul, li { ... } as shown below.

ul,
li {
  display: inline;
}
  • item 1
  • item 2
  • item 3

I like using the flexbox approach because it gives me a access to all of the nice alignment properties like align-items: center; and justify-content: flex-start; ect that I wouldn’t get with the display inline approach.

Just for posterity, below is I’d create ul li horizontal list using tailwindcss. The first example uses the flexbox approach and the second uses the display inline approach. The first one clearly requires less code, especially if your list contains a lot of items.

<ul class="flex">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ul>
<ul>
  <li className="inline">item 1</li>
  <li className="inline">item 2</li>
  <li className="inline">item 3</li>
</ul>