Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining CSS Pseudo-elements, ":after" the ":last-child"

Tags:

css

People also ask

How do you add multiple pseudo elements in CSS?

Adding multiple pseudo elementsYou can combine several CSS pseudo-elements for one element. However, you cannot use CSS ::after two times or ::before two times. In the example below, the first letter of <div> is green and has x-large font size. The first line of <div> element is red and has small capital letters.

Can pseudo elements and pseudo classes be combined?

There are no special rules around combining pseudo-classes and pseudo-elements, besides the one rule that says there can only be one pseudo-element per complex selector and it must appear at the very end.

How do I skip the last child in CSS?

The :not() selector excludes the element passed to it from selection. The :last-child selector selects the last child. Combining these two above selector to excludes the last children (inner-div) of every parent div from the selection.

Can pseudo elements combine?

If you're talking about pseudo-classes, then yes, you can combine them in any order.


This works :) (I hope multi-browser, Firefox likes it)

li { display: inline; list-style-type: none; }
li:after { content: ", "; }
li:last-child:before { content: "and "; }
li:last-child:after { content: "."; }
<html>
  <body>
    <ul>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
    </ul>
  </body>
</html>

I do like this for list items in <menu> elements. Consider the following markup:

<menu>
  <li><a href="/member/profile">Profile</a></li>
  <li><a href="/member/options">Options</a></li>
  <li><a href="/member/logout">Logout</a></li>
</menu>

I style it with the following CSS:

menu > li {
  display: inline;
}

menu > li::after {
  content: ' | ';
}

menu > li:last-child::after {
  content: '';
}

This will display:

Profile | Options | Logout

And this is possible because of what Martin Atkins explained on his comment

Note that in CSS 2 you would use :after, not ::after. If you use CSS 3, use ::after (two semi-columns) because ::after is a pseudo-element (a single semi-column is for pseudo-classes).


An old thread, nonetheless someone may benefit from this:

li:not(:last-child)::after { content: ","; }
li:last-child::after { content: "."; }

This should work in CSS3 and [untested] CSS2.


You can combine pseudo-elements! Sorry guys, I figured this one out myself shortly after posting the question. Maybe it's less commonly used because of compatibility issues.

li:last-child:before { content: "and "; }

li:last-child:after { content: "."; }

This works swimmingly. CSS is kind of amazing.