有没有一种方法只针对 <h1>
标签中的直接文本进行操作?
以下是我想要实现的示例:
<h1>I want to select this text with a css selector <small>but not this text</small></h1>
这似乎不起作用:
h1:not(small)
这真的可能吗?
有没有一种方法只针对 <h1>
标签中的直接文本进行操作?
以下是我想要实现的示例:
<h1>I want to select this text with a css selector <small>but not this text</small></h1>
这似乎不起作用:
h1:not(small)
这真的可能吗?
h1:not(small)
您的选择器 h1:not(small)
不起作用,因为它的意思是:
目标所有不是
small
元素的h1
元素。
这与仅使用 h1
选择器相同。
h1 :not(small)
您应该使用h1 :not(small)
,它表示:
选择所有
h1
的后代元素,但不包括small
元素。
太棒了!正是您想要的。
但是,直接包含在元素内部的文本(即没有标签的文本)会成为匿名元素。而CSS无法选择匿名元素。
h1 :not(small) {
color: orange;
}
<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>
要排除small
元素,它必须将自己标识为h1
的子元素。
但是CSS中没有父选择器。
您需要两个选择器来使其生效:
h1 {
color: orange;
}
h1 > small {
color: black;
}
<h1>I want to select this text with a css selector <small>but not this text</small></h1>
h1
下的任何非h1
子元素。它并没有排除span
继承其父级样式的可能性... - agrm对 h1
应用样式,然后在 small
中还原这些更改。例如,如果您只想更改颜色,则可以使用以下代码:
h1 { color: red; }
h1 small { color: initial; }
或者,如果您有多个样式更改;
h1 {
color: red;
font-weight: italic;
text-transform: uppercase;
}
h1 small {
color: initial;
font-weight: initial;
text-transform: initial;
}
initial
CSS 值可在除 IE 和 Opera Mini 之外的所有浏览器上使用。请查看this page以获取更多信息。
<small>
中的内容进行设置,并取消你刚刚为<h1>
设置的内容。 - tao