48

What is the proper CSS syntax for applying multiple pseudo classes to a selector. I'd like to insert "," after each item in a list except the last one. I am using the following css:

ul.phone_numbers li:after {
    content: ",";
}

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

This works fine on FF3, Chrome and Safari 3. IE7 doesn't work because it doesn't support :after (as expected). In IE 8 this renders with a comma after each li including the last one. Is this a problem with IE8 or is my syntax incorrect? It's ok if it doesn't work in IE8 but I would like to know what the proper syntax is.

Brian Fisher
  • 23,519
  • 15
  • 78
  • 82

5 Answers5

60

:last-child is a pseudo-class, whereas :after (or ::after in CSS3) is a pseudo-element.

To quote the standard:

Pseudo-classes are allowed anywhere in selectors while pseudo-elements may only be appended after the last simple selector of the selector.

This means your syntax is correct according to CSS2.1 and CSS3 as well, i.e. IE8 still sucks ;)

Christoph
  • 164,997
  • 36
  • 182
  • 240
9

You could use the adjacent sibling selector:

ul.phone_numbers li + li:before {
   content: ",";
}
Gumbo
  • 643,351
  • 109
  • 780
  • 844
4

There is no problem nesting pseudo class selectors as long as the rules applied match the particular element in the DOM-tree . I want to echo the possibilities of styling with pseudo class selectors from w3 website . That means you can also do stuff like :

.ElClass > div:nth-child(2):hover {
    background-color: #fff;
    /*your css styles here ... */
}
drneel
  • 2,887
  • 5
  • 30
  • 48
big kev
  • 307
  • 2
  • 8
3

You can get around this by having a another tag inside the <li/> and apply the :after to that instead. That way you would be applying the :last-child and :after to different elements:

ul.phone_numbers li > span:after {
    content: ",";
}

ul.phone_numbers li:last-child > span:after {
    content: "";
}
Linus Caldwell
  • 10,908
  • 12
  • 46
  • 58
DonutReply
  • 3,184
  • 6
  • 31
  • 34
1

IE8 doesn't support last-child :( They're focused on sorting out CSS 2.1 support it looks like. Why microsoft haven't adopted Gecko or Webkit yet I don't know.

http://msdn.microsoft.com/en-us/library/cc351024(VS.85).aspx#pseudoclasses

roborourke
  • 12,147
  • 4
  • 26
  • 37