Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 919
twhb Avatar asked Oct 17 '22 03:10

twhb


1 Answers

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.

like image 84
Michael Benjamin Avatar answered Oct 21 '22 08:10

Michael Benjamin