我有以下字符串,我想使用 css 选择器忽略字符串中的强标记:
<p><strong>Local:</strong><br>
-Brasília/DF </p>
我尝试了以下语法,但它不起作用。
p:not(strong)
我哪里错了?
最佳答案
一个伪类,附加到一个元素p:not(strong)
, 从它“附加”的那些元素中选择(这里是 p
);和一个 <p>
元素总是不是<strong>
元素;因此这个选择器总是匹配每一个 <p>
元素。
您似乎在尝试设置父项的样式 <p>
基于其子元素的元素 <strong>
无法工作的元素,因为 CSS 没有父选择器(参见:“Is there a CSS parent selector?”)
相反,您可以向 <p>
添加一个类(或其他属性)元素,并在选择器中使用它:
<p class="hasStrongDescendant"><strong><strong>Local:</strong><br>
-Brasília/DF </p>
和样式:
p:not(.hasStrongDescendant) {
/* CSS here */
}
p:not(.hasStrongDescendant) {
color: orange;
}
<p>A paragraph with no child elements</p>
<p class="hasStrongDescendant"><strong>Local:</strong>
<br>-Brasília/DF</p>
或者,使用 data-*
属性:
<p data-hasChild="strong"><strong>Local:</strong><br>
-Brasília/DF </p>
和样式:
p:not([data-hasChild="strong"]) {
/* CSS here */
}
p:not([data-hasChild="strong"]) {
color: #f90;
}
<p>A paragraph with no child elements</p>
<p data-hasChild="strong"><strong>Local:</strong>
<br>-Brasília/DF</p>
此外,如果您包装了 <p>
的内容, 在 <strong>
之后,在它们自己的元素中,您可以使用否定选择器为段落的后代设置样式:
<p>A paragraph with no child elements</p>
<p><strong>Local:</strong>
<br><span>-Brasília/DF</span>
</p>
样式:
p :not(strong) {
/* note the space between the
'p' and the ':not()' */
color: #f90;
}
p :not(strong) {
color: #f90;
}
<p>A paragraph with no child elements</p>
<p><strong>Local:</strong>
<br><span>-Brasília/DF</span>
</p>
另外两种方法,假设您想要在 <strong>
之外设置子项文本的样式元素是(最简单的):
/* define a colour for the <p>
elements: */
p {
color: #f90;
}
/* define a colour for the <strong>
elements within <p> elements: */
p strong {
color: #000;
}
p {
color: #f90;
}
p strong {
color: #000;
}
<p>A paragraph with no child elements</p>
<p><strong>Local:</strong>
<br>-Brasília/DF</p>
还有一个稍微复杂的版本,使用 CSS 生成的内容:
p {
color: #f90;
}
p[data-label]::before {
content: attr(data-label) ': ';
color: #000;
display: block;
font-weight: bold;
}
<p data-label="Local">-Brasília/DF</p>
引用资料:
关于css - :not() selector not selecting element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37941641/