1

I want to target the <code> tag in sample 1, but not sample 2:

Sample 1: <p><code>foo()</code> describes the function</p>
Sample 2: <p>Other text comes first, <code>bar()</code> is not at the beginning</p>

the code:first-child selector does not regard the text-node "Other text comes first" as a child element.

Any ideas, on whether I can handle this in pure CSS (I know how to do it with JS or by altering the HTML code, but that's not what is needed)

random_user_name
  • 25,694
  • 7
  • 76
  • 115
Philipp
  • 10,240
  • 8
  • 59
  • 71

2 Answers2

1

Unfortunately, no.

Not with pure CSS. There is no "first node of parent element without any text before it" selector.

Even with a combination of child combinator and the various sibling selectors (adjacent and / or general), this is not possible.

In fact, a javascript solution to this would be non-trivial to author, even if using jQuery.

random_user_name
  • 25,694
  • 7
  • 76
  • 115
1

In the context given, I also don't think this is possible.

If you are able to manage everything within a single element (in this case, a singular <p> element), you can use the CSS :first-of-type selector, which matches every element that is the first child, of a particular type, of its parent:

<!DOCTYPE html>
<html>
<head>
<style> 
.colorMe code:first-of-type {
  background: red;
}
</style>
</head>
<body>

<p class="colorMe">
  <code>foo()</code> describes the function<br />
  Other text comes first, <code>bar()</code> is not at the beginning
</p>

<p>
  <code>foo()</code> describes the function<br />
  Other text comes first, <code>bar()</code> is not at the beginning
</p>

</body>
</html>

In this case, only the first code element would be targeted with the CSS. You can see that in action here. More info on CSS :first-of-type selector.

Hope this helps :)

Sam Sverko
  • 1,480
  • 4
  • 15
  • 32