Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to specify a CSS shorthand for "all elements except the first/last"?

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?

like image 371
julien_c Avatar asked Apr 05 '12 17:04

julien_c


People also ask

How do I select all except first child CSS?

Use the :not(selector) Selector Not to Select the First Child in CSS. We can use the :not(selector) selector to select every other element that is not the selected element. So, we can use the selector not to select the first child in CSS.

How do I skip the first element in CSS?

I think :nth-child() will do the trick. This styles all of the p tags except for the first because it starts on the 2nd child. You could then style the first p tag separately with p:first-child .

Does order of attributes matter in CSS?

CSS Order MattersIn CSS, the order in which we specify our rules matters. If a rule from the same style sheet, with the same level of specificity exists, the rule that is declared last in the CSS document will be the one that is applied.


1 Answers

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.

like image 71
BoltClock Avatar answered Oct 18 '22 16:10

BoltClock