如何选择没有前导或尾随文本节点的元素?

时间:2022-01-06 22:15:49

I experimented with using the :only-child pseudo-class but unfortunately this does not seem to consider the text nodes:

我尝试使用:独生子女伪类,但不幸的是,这似乎没有考虑到文本节点:

<style type="text/css">
  div span:only-child {
    color: red;
  }
</style>

<div>
  Test
  <span>This still becomes red :(</span>
</div>

<div>
  <span>This becomes red, as it should!</span>
</div>
<div>
  <span>This does not become red - great!</span>
  <span>This does not become red - great!</span>
</div>

I am trying to find a way to detect when a specific element is completely alone within its container element in a situation where I am unable to introduce new classes.

我试图找到一种方法,在无法引入新类的情况下,检测特定元素在其容器元素中何时是完全独立的。

Is there a way to achieve this with CSS?

有办法用CSS实现这一点吗?

2 个解决方案

#1


3  

Is there a way to achieve this with CSS?

有办法用CSS实现这一点吗?

Unfortunately, not.

不幸的是,没有。

Included in an old revision of the CSS Working Group "mistakes" list is missing the idea that..

在CSS工作组“错误”列表的一个旧版本中,缺少了……

No naked text mixing with elements. All raw text should have an addressable, stylable element wrapping it, created by CSS if necessary.

没有与元素混合的裸文本。所有原始文本都应该有一个可寻址的、可样式的元素来包装它,如果需要的话,由CSS创建。

Current list

当前列表

Text Nodes are not element and CSS can't select (or ignore) elements that don't exist.

文本节点不是元素,CSS不能选择(或忽略)不存在的元素。

So, it's probably best practice to always use a text element when incorporating text in a page...you never know when you might need to style it.

因此,在将文本合并到页面中时,最好总是使用文本元素……你永远不知道什么时候你需要设计它。

#2


0  

div:nth-child(2) span {
color: red;
}

https://jsfiddle.net/cmckay/8663aLcg/

https://jsfiddle.net/cmckay/8663aLcg/

#1


3  

Is there a way to achieve this with CSS?

有办法用CSS实现这一点吗?

Unfortunately, not.

不幸的是,没有。

Included in an old revision of the CSS Working Group "mistakes" list is missing the idea that..

在CSS工作组“错误”列表的一个旧版本中,缺少了……

No naked text mixing with elements. All raw text should have an addressable, stylable element wrapping it, created by CSS if necessary.

没有与元素混合的裸文本。所有原始文本都应该有一个可寻址的、可样式的元素来包装它,如果需要的话,由CSS创建。

Current list

当前列表

Text Nodes are not element and CSS can't select (or ignore) elements that don't exist.

文本节点不是元素,CSS不能选择(或忽略)不存在的元素。

So, it's probably best practice to always use a text element when incorporating text in a page...you never know when you might need to style it.

因此,在将文本合并到页面中时,最好总是使用文本元素……你永远不知道什么时候你需要设计它。

#2


0  

div:nth-child(2) span {
color: red;
}

https://jsfiddle.net/cmckay/8663aLcg/

https://jsfiddle.net/cmckay/8663aLcg/