Published: July 16, 2018
CSS: Align ::before items vertically with content
How do I align a custom list-style/bullet point in a list with CSS? You use flexbox!
Here's what I wanted to achieve: a menu in a header that looked like this:
Item One | Item Two | Item Three
Here's my HTML:
<ul class="menu">
<li class="menu-item">Item One</li>
<li class="menu-item">Item Two</li>
<li class="menu-item">Item Three</li>
<li class="menu-item">Item Four</li>
</ul>
And my corresponding CSS:
.menu {
display: flex;
}
.menu-item {
margin-left: 1rem;
}
.menu-item + .menu-item::before {
content: "|";
}
Now, to get the | (pipe character) to display inline with the .menu-item is something I always have to think about. Do I float: left, or position: relative, or display: inline, or something else? As it turns out, it’s simple, and I've no idea why I never thought of it before: just use flexbox on the <li> element.
.menu-item {
margin-left: 1rem;
display: flex;
}
This post was inspired by a comment on this StackOverflow post: Vertically aligning CSS :before and :after content