如何定位标签中的直接文本而不是文本?

Jii*_*iiB 5 html css css-selectors css3

有没有办法只针对<h1>-Tag中的直接文本?

这是我想要做的一个例子:

<h1>I want to select this text with a css selector <small>but not this text</small></h1>
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用:

h1:not(small)
Run Code Online (Sandbox Code Playgroud)

它甚至可能吗?

Mic*_*l_B 6

h1:not(small)

您的选择器h1:not(small)不起作用,因为它说:

定位所有h1不是small元素的元素。

这与单独使用h1选择器相同。


h1 :not(small)

你会更接近h1 :not(small),它说:

以一个h1exceptsmall元素的所有后代为目标。

繁荣!正是你想要的。

除了直接包含在元素内部的文本(即周围没有标签的文本)成为匿名元素。而匿名元件不被CSS选择

h1 :not(small) {
  color: orange;
}
Run Code Online (Sandbox Code Playgroud)
<h1>This text is contained directly inside the container. It is not selectable by CSS. It is an anonymous element. <small>This text is inside a small element</small></h1>

<hr>

<h1><span>This text is contained in a span. It is selectable by CSS</span> <small>This text is inside a small element</small></h1>
Run Code Online (Sandbox Code Playgroud)


CSS 父选择器

对于small要排除的元素,它必须将自己标识为 的子元素h1

但是CSS 中没有父选择器


解决方案:两个选择器

您需要两个选择器来完成这项工作:

  • 第一个在父项上设置样式。
  • 第二个覆盖子级的第一个。

h1 {
  color: orange;
}

h1 > small {
  color: black;
}
Run Code Online (Sandbox Code Playgroud)
<h1>I want to select this text with a css selector <small>but not this text</small></h1>
Run Code Online (Sandbox Code Playgroud)


更多信息