5

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.

Michael Benjamin
  • 265,915
  • 79
  • 461
  • 583
twhb
  • 3,383
  • 2
  • 14
  • 21
  • Can you just wrap the remaining text in a span, like so:

    foo bar

    ? Then your selector code:first-child would work.
    – deadfishli Oct 24 '17 at 21:39
  • 1
    I think that's the whole point of the question to not do that. If you'd wrap it then you could do a `:last-of-type`. But that's not the question here. I think it is not possible with pure CSS. – lumio Oct 24 '17 at 21:42
  • 1
    Possible duplicate of [Is there a CSS selector for text nodes?](https://stackoverflow.com/questions/5688712/is-there-a-css-selector-for-text-nodes) – Julio Feferman Oct 24 '17 at 21:45
  • 1
    @deadfishli yes, that works, I'm asking though if there's a solution that doesn't clutter the HTML. – twhb Oct 24 '17 at 21:49

2 Answers2

3

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.

Michael Benjamin
  • 265,915
  • 79
  • 461
  • 583
0

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.

BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284