Skip to content
Jabran Rafique

CSS pseudo elements

1 minute read

I was styling a site's navigation recently and needed a bullet between each item. The usual way to do that is with the ::after or ::before pseudo element, so that's what I reached for. The markup is a plain unordered list:

<div class="site">
  <ul class="site__nav">
    <li class="site__nav-item">Home</li>
    <li class="site__nav-item">Foo</li>
    <li class="site__nav-item">Bar</li>
    <li class="site__nav-item">Baz</li>
  </ul>
</div>

And the CSS for it:

.site__nav {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
.site__nav-item {
  display: inline-block;
  position: relative;
  margin-left: 10px;
}

This adds a bullet after each item with ::after:

.site__nav-item::after {
  position: absolute;
  display: inline-block;
  content: '\2022';
  color: #ddd;
  line-height: inherit;
  margin-left: 10px;
}

That leaves a stray bullet after the last item, which looks odd. There are two common ways to get rid of it.

Hide it

.site__nav-item:last-child::after {
  display: none;
}

Empty its content

.site__nav-item:last-child::after {
  content: ' ';
}

Either way the pseudo element still exists. You've only hidden it or blanked it out. With the :not selector the browser never creates it for the last item, so there's nothing to hide:

.site__nav-item:not(:last-child)::after {
  position: absolute;
  display: inline-block;
  content: '\2022';
  color: #ddd;
  line-height: inherit;
  margin-left: 10px;
}

I haven't tested whether it makes any difference to performance, but it reads better and I'd go with it.