twhb
twhb

Reputation: 4594

Is it possible to select elements not preceded by text?

I want a CSS selector that matches the <code> in:

<p><code>foo</code> bar</p>

but not the <code> in:

<p>foo <code>bar</code></p> 

code:first-child doesn't work. It matches both.

Asking just because I don't think it's possible.

I figured I'd give the community a shot before giving up.


Edit - people keep marking this as duplicate, so let me be clear: if the current top answer is correct then the answer to the question you're referencing has the same root cause, but that does not make it the same question. It is entirely possible for the answers to the two questions to differ--or if it isn't, the "why" of that is an answer only to this question, not that one.

Upvotes: 5

Views: 617

Answers (2)

BoltClock
BoltClock

Reputation: 723468

Selectors does not make a distinction between an only child element that's the only child node of its parent, and an only child element that has one or more sibling text nodes. In both cases, the child element will match :only-child; the text nodes are not significant in the latter case.

Upvotes: 0

Michael Benjamin
Michael Benjamin

Reputation: 371093

There are two elements in your paragraph.

<code>bar</code>

and

<anonymous-inline-box>foo</anonymous-inline-box>

Anonymous inline elements are automatically generated and cannot be targeted by CSS. Therefore, there is no way to apply styles to the code element relative to the text node.

If wrapping the text in an actual element isn't an option, then try JavaScript.

Here are some more details from the spec:

9.2.2.1 Anonymous inline boxes

Any text that is directly contained inside a block container element must be treated as an anonymous inline element.

Such anonymous inline boxes inherit inheritable properties from their block parent box.

Upvotes: 3

Related Questions