How to set separator between list element properly with CSS and HTML?

Viewed 613

I have a simple list like this, and I want to use | as the separator between each list item. How can I do this properly?

ul{
  display: flex;
  justify-content: space-evenly;
  align-items: center
}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

Current output: Item 1 Item 2 Item 3

Expected output: Item 1 | Item 2 | Item 3

The easiest way I can think of is to include the separator as an HTML element, it does look good to me for wrapping it with <li>, as their content semantically is irrelevant with the list. Besides, using a tag other than <li> in <ul>/<ol> is forbidden.

What is the best way to approach this issue?

3 Answers

Try using border which is the easiest way to achieve.

ul {
  display: flex;
  padding: 0;
  margin: 0;
  list-style-type: none;
}
li:not(:last-child) {
  margin-right: 5px;
  padding-right: 5px;
  border-right: 1px solid;
}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

You can user after element in your li to assign | every after li.

ul{
  diplay: flex;
  justify-content: space-evenly;
  align-items: center
}

ul li {
  position:relative;
  margin:0 2px;
  padding:0 2px;
  display:inline-block;
  vertical-align:top;
}
ul li:after {
  position:absolute;
  content:'|';
  right:-5px;
}
ul li:first-child {
  margin-left:0;
}
ul li:last-child {
  margin-right:0;
}

It's unclear whether you want to retain the bullet point markers or the <ul>'s default left padding. Assuming you don't, you can simply use display:contents with a ::before pseudo-element on each <li> element except the first to make the separators their own flex-items. Like this:

ul{
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  padding: 0;
}
li {
  display: contents;
}
li + li::before {
  content: '|';
}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

If you do want the bullet point markers, you'll need to add another element inside the <li> elements to restore them. Like this:

ul{
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  padding: 0;
}
li {
  display: contents;
}
li + li::before {
  content: '|';
}
li > span {
  display:list-item;
}
<ul>
  <li><span>Item 1</span></li>
  <li><span>Item 2</span></li>
  <li><span>Item 3</span></li>
</ul>

Related