是否有第一个孩子的CSS选择器,并考虑了文本节点? [英] Is there a CSS selector for the first child, taking text nodes into account?

查看:89
本文介绍了是否有第一个孩子的CSS选择器,并考虑了文本节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to find a CSS selector for an element that is the first child, taking any text nodes into account that might come before it (i.e. if any elements come before, possibly unwrapped text nodes, this is no longer considered the first child).

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

But it seems :first-child does not include text nodes, neither does :nth-child, etc.

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

This is where I'm at, but it's not working:

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

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

Unfortunately I have little control over the markup.

我知道这已经向我们提出了,但是那是3年前,而在前端已经有1000多年了!

I'm aware this has been asked before, but that was 3 years ago, which is as good as a thousand years in front-end!

推荐答案

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

One workaround could be to make use of the :empty pseudo class. You will need more markup though.

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选择器,并考虑了文本节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆