是否有第一个孩子的CSS选择器,考虑文本节点?

Jos*_*son 8 css

我正在尝试为第一个子元素找到一个CSS选择器,考虑任何可能在它之前的文本节点(即如果之前有任何元素,可能是未包装的文本节点,这不再被认为是第一个孩子).

但它似乎:first-child不包括文本节点,也不包括:nth-child等等.

这就是我所处的位置,但它不起作用:

.red-if-not-first {
  color: red;
  font-weight: bold;
}

.red-if-not-first:first-child {
  color: green;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

不幸的是,我几乎无法控制标记.

我知道之前有人问过这个问题,但那是3年前的事情,这在前端已有一千年了!

小智 7

如果由于某种奇怪的原因,您可以只支持 Gecko,那么您可以使用-moz-first-node选择器来做到这一点。

https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-first-node


Mr *_*ter 5

一种解决方法可能是使用:empty伪类.你需要更多的标记.

p .red-if-not-first {
  color: red;
  font-weight: bold;
}

p > :empty + .red-if-not-first {
  color: green;
}
Run Code Online (Sandbox Code Playgroud)
<p>
  <span>Lorem ipsum.</span> <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></span> <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>
Run Code Online (Sandbox Code Playgroud)


Tru*_*gDQ 2

这是2017年。答案是“否”。没有这样的 CSS 选择器可以帮助你解决这个问题。

  • 此外,不应仅仅为了区分已经明显的内容而注入标记。:first-node 将是对 CSS 规范的一个很好的补充。 (5认同)