Eric Herlitz
Eric Herlitz

Reputation: 26267

Select all but first element using CSS3

I need to select all headers but the first

<div class="block">
    <div class="header">first</div>
</div>
<div class="block">
    <div class="header">second</div>
</div>
<div class="block">
    <div class="header">third</div>
</div>
<div class="block">
    <div class="header">fourth</div>
</div>

Using jquery I would do this $(".header:not(:first)"), I'm however restricted to CSS/CSS3. I cannot tag the elements other than in my example.

Using .header:not(:first-child) wont do the trick

Upvotes: 6

Views: 5432

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240928

The .header elements are not siblings, therefore you should probably select all but the first .block element, then select the descendant .header from there:

.block:not(:first-child) .header {}

Depending on your markup, you may also want to negate the first of type if the element's types differ:

.block:not(:first-of-type) .header {}

.block:not(:first-child) .header {
  color: #f00;
}
<div class="block">
    <div class="header">first</div>
</div>
<div class="block">
    <div class="header">second</div>
</div>
<div class="block">
    <div class="header">third</div>
</div>
<div class="block">
    <div class="header">fourth</div>
</div>

As David Thomas points out, you can also use the adjacent sibling combinator, + or the general sibling combinator, ~ in order to select all following siblings:

.block ~ .block .header {}

or:

.block + .block .header {}

.block + .block .header {
  color: #f00;
}
<div class="block">
    <div class="header">first</div>
</div>
<div class="block">
    <div class="header">second</div>
</div>
<div class="block">
    <div class="header">third</div>
</div>
<div class="block">
    <div class="header">fourth</div>
</div>

Upvotes: 12

Related Questions