I would like to select the first occurrance of <p>
after each <h1>
and <h2>
when all these tags are sibligs (i.e. all belong to the same div). Paragraph does not necessarily follow the header immediately; there could be some images, or tables, or other elements in between.
The aim is to then style the first letter of such paragraphs. I do not want to use javascript or jQuery. Is this possible with css selectors only?
For example I would have something like:
<div>
<h1>Bla</h1>
<p class="Testo">BlaBla.</p> <!-- #1 -->
<p class="Testo">BlaBla.</p> <!-- #2 -->
<h2>BlaBlaBla</h2>
<p class="Testo">BlaBla.</p> <!-- #3 -->
<h2>BlaBlaBla</h2>
<div>
<img>
<p></p> <!-- #4 -->
</div>
<p class="Testo">BlaBla.</p> <!-- #5 -->
</div>
And I would like to select #1, #3 and #5. I am lost by now and appreciate some help.
If I use: h1 + p.Testo:first-letter
and h2 + p.Testo:first-letter
it does not select #5 because it is not following the header immediately.
If I use: h1 ~ p.Testo:first-letter
and h2 ~ p.Testo:first-letter
it selects also #2 because that is also a sibling of h1
.
If I use h1 > p.Testo:first-letter
and h2 > p.Testo:first-letter
it selects none of them because they are siblings and not children; same for descendant selector h1 p.Testo:first-letter
and h2 p.Testo:first-letter
If I use: h1 ~ p.Testo:first-of-type:first-letter
and h2 ~ p.Testo:first-of-type:first-letter
it selects only #1...
The "first occurrence of X after H" selector does not exist.
The closest pure-CSS solution is (add class="h"
to each of your <h1>
, <h2>
elements, or repeat the selectors for h1
, h2
, ..):
.h + p.Testo,
.h + *:not(p.Testo) + p.Testo,
.h + *:not(p.Testo) + *:not(p.Testo) + p.Testo,
.h + *:not(p.Testo) + *:not(p.Testo) + *:not(p.Testo) + p.Testo {
/* repeat + *:not(p.Testo) for each additional sibling */
color: red;
}
I am a little late, but for future people looking forward to resolve this, you can actually use css3 pseudo selector ::first-of-type (read more here) like this
p:first-of-type {
color: #f00;
}
if you want it to be the first within one particular div
you can use
div#id_div > p:first-of-type {
background: #ff0000;
}
and that should do the trick! hope this help anyone still looking for this answer
I know the question is answered, but using sass could be really cool as well
h1, h2, h3, h4
{
& + p
{
color:red;
}
}
Where & represent the parent element, once compiled it will turn it into
h1 + p { color:red }
h2 + p { color:red }
h3 + p { color:red }
h4 + p { color:red }
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