I'm trying to find a CSS selector for an element that is the first child, taking any text nodes into account that might come before it (i.e. if any elements come before, possibly unwrapped text nodes, this is no longer considered the first child).
But it seems :first-child
does not include text nodes, neither does :nth-child
, etc.
This is where I'm at, but it's not working:
.red-if-not-first {
color: red;
font-weight: bold;
}
.red-if-not-first:first-child {
color: green;
}
<p>
Lorem ipsum. <span class="red-if-not-first">This should be red, not green, because some content comes before it.</span> Eum natus culpa officia a molestias, sed beatae aut in autem architecto iure repellat quam placeat, expedita maxime laborum necessitatibus repudiandae. Corrupti!
</p>
<p>
<span class="red-if-not-first">This is rightly green, not red, because it's first bit of content in this paragraph.</span> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum natus culpa officia a molestias, sed beatae aut in autem architecto iure repellat quam placeat, expedita maxime laborum necessitatibus repudiandae. Corrupti!
</p>
Unfortunately I have little control over the markup.
I'm aware this has been asked before, but that was 3 years ago, which is as good as a thousand years in front-end!
In essence, you're asking if text can affect the styling of dom elements and the answer is - no, because text is not a dom element of it's own.
We can prove this with a simple experiment. Just add a marker element at the beginning of the paragraph and then use a sibling selector to override color. You'll see that this works in both cases, because text has no effect on surrounding dom flow.
For the record, I thought I was onto something by initially doing this marker experiment with
::before
pseudo elements but they can't be used with sibling selectors either. Pseudo elements are not real elements and will have no effect on the relationships of actual dom tree.One workaround could be to make use of the
:empty
pseudo class. You will need more markup though.This is 2017. The answer is "No". There is no such CSS selector that can help you with this.
If, for some strange reason, you can make do with only supporting Gecko, you can use
-moz-first-node
selector to do this.https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-first-node