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

但是:first-child似乎不包括文本节点,:nth-child也不包括文本节点。

这是我所在的位置,但不起作用:



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

.red-if-not-first:first-child {
  color: green;
}

<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>





不幸的是,我对标记几乎没有控制权。

我知道这已经是asked before了,但是那是3年前了,它在前端已经有1000多年了!

最佳答案

一种解决方法是利用:empty伪类。不过,您将需要更多标记。



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

p > :empty + .red-if-not-first {
  color: green;
}

<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>

关于css - 考虑到文本节点,第一个 child 是否有CSS选择器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46976921/

10-12 03:34