Is there a way to specify a CSS shortcut for & ldquo; all items except the first / last?

advertisements

Very often, it's natural to need to specify a CSS style for all elements except the first (or the last). For example, when styling paragraphs, you wish to add a bottom margin to every element except the last one (or similarly, a top margin to every element except the first one).

Is there any way to do that that's :

  • more concise than defining p {...} and then p:first-child {...}?
  • more straightforward and intuitive than p:nth-child(-n+1)?

If there is not, do you know of any attempt at adding it?


For all p elements except the first child, use either one of these (the second one is better-supported):

p:not(:first-child)
p:first-child ~ p

For all p elements except the last child:

p:not(:last-child)

For all p elements except the first and the last children:

p:not(:first-child):not(:last-child)

As usual, CSS3's :not() and :last-child aren't supported until IE9+ and relatively new versions of other browsers. You're not going to reach very far in terms of browser support (IE8 and older) unless you add classes to your first and last children, using JavaScript or otherwise.

Remember that vertical margins collapse between in-flow paragraphs and their ancestor(s), so unless you want to zero out the margins of the container element for these paragraphs as well, you shouldn't need to zero out the margins of the first and last p elements specifically. Here's a fiddle to illustrate.