Paul Dessert
Paul Dessert

Reputation: 6389

removing last element created by ::after pseudo-element

I'm creating a nav menu and I'm using the ::after pseudo-element and I want to achieve this:

home | about | articles | personal projects

This is my css code:

nav ul li::after{
    content: " | ";
}

This is my HTML markup:

<nav class="wrapper">
    <ul>
        <li><a href="/">home</a></li>
        <li><a href="/about.php">about</a></li>
        <li><a href="/articles.php">articles</a></li>
        <li><a href="/projects.php">personal projects</a></li>
    </ul>
</nav>

Everything is good except for ::after is adding a | at the very end (as expected)

ex:

home | about | articles | personal projects |

Is there any way, only using css, to remove the last |?

I know I can use Javascript, or simply add this to my HTML. I'm looking for a pure CSS solution.

Upvotes: 5

Views: 8787

Answers (4)

Vitorino fernandes
Vitorino fernandes

Reputation: 15951

nav ul li:not(:last-child)::after{
  content: " | ";
}

The negation CSS pseudo-class, :not(X), is a functional notation taking a simple selector X as an argument. It matches an element that is not represented by the argument. X must not contain another negation selector.

The specificity of the :not pseudo-class is the specificity of its argument. The :not pseudo-class does not add to the selector specificity, unlike other pseudo-classes.

https://developer.mozilla.org/en-US/docs/Web/CSS/:not

In simple it will not add styles for the :last-child

Upvotes: 3

enguerranws
enguerranws

Reputation: 8233

Or, you can use a simple CSS2 piece of code :

nav ul li + li:before {
   content: " | ";
}

And you won't have to worry about the last one. Elegant, compatible.

Sometimes, it's way more simple to use good old CSS selectors in the right way :)

Upvotes: 10

lharby
lharby

Reputation: 3265

Yep

 nav ul li:last-child::after {
   content: "";
}

jsfiddle

Upvotes: 1

Tomek Buszewski
Tomek Buszewski

Reputation: 7935

A little long, but works:

nav ul li:last-child::after { content:''; }

or

nav ul li:last-child::after { display: none; }

Codepen

Upvotes: 5

Related Questions