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 thenp: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
pelements except the first child, use either one of these (the second one is better-supported):For all
pelements except the last child:For all
pelements except the first and the last children:As usual, CSS3’s
:not()and:last-childaren’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
pelements specifically. Here’s a fiddle to illustrate.