我正在尝试为作为第一个子元素的元素找到一个 CSS 选择器,并考虑可能出现在它之前的任何文本节点(即,如果有任何元素出现在前面,可能是未包装的文本节点,则不再考虑第一个 child )。
但是好像: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 ,不过那是三年前的事了,这在前端不亚于一千年!
最佳答案
如果出于某种奇怪的原因,您只能勉强支持 Gecko,则可以使用-moz-first-node
选择器来做到这一点。
https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-first-node
关于css - 考虑到文本节点,第一个 child 是否有 CSS 选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42074295/