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
The trick is very easy, in CSS we have the sibling selector ("+"), if i will make selector that choose "li + li" it will select all list-items except the first . That's all!
We can very easily achieve this using the :not and :first-child selectors in a combination. For example, if you want to select all paragraphs except the first one that are inside a div element, you can use div :not(:first-child) selector.
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. We can use :first-child as the selector in the :not(selector) selector.
The :first-child selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With