css 如果通用选择器具有特定的属性值组合,我可以样式化元素吗?

piok6c0g  于 2023-04-01  发布在  其他
关注(0)|答案(2)|浏览(116)

这是专门为text-spacing样式。我想设置元素的自动高度/宽度的字母间距/单词间距有一些特定的值。

超文本标记语言

<span class="subjectText">this is the text</span>

万能选择器

*{
  letter-spacing:1.641px;
}

所需样式

*[style*="letter-spacing:1.614px"] .subjectText{
     background-color:yellow;
}

我试过下面,但它不工作

*[style*="letter-spacing:1.614px"] .subjectText{
     background-color:yellow;
}
nsc4cvqm

nsc4cvqm1#

已更新

简短的回答是:目前,有一种方法可以测试已定义CSS规则的单个 properties,并使用它们的值来定义进一步的CSS规则。无论它们是使用 universal 还是 specific 选择器定义的,CSS attribute selector 机制根本不包含对 properties 的测试。
一个简单的测试表明,它将适用于inline style attributes,但您需要将!important添加到您想要覆盖的属性中,因为 inline style attributes<tag style=".." />)优先于 in document styles<head><style>...</style></head>)。
在当前的构造中,'*'-通用选择器是偶数[OPTIONAL],因为[attribute]选择器规则足够常见。
但是要注意,CSS属性规则[style*="..."]必须与标签style="..."赋值完全匹配。如果不完全匹配,则会失败。

/* Testing any CSS property will NOT work */
 *                       { color: orange }
[style*="color: orange"] { color: black }

/* Testing the inline 'style' attribute will work */
[style*="color: red"]   { color: black !important }
[style*="color: green"] { font-weight: bold; color: black }
[style*="color: blue"]  { color: black }

h3 { color: black }
<h3>for this to work, '*'-universal selector in the CSS is not required:</h3>

<p>This is the first test line. It is 'orange' and will not become 'black' as the CSS required by OP does not work.</p><p style="color: red">This is a test line. It is 'red', but will become 'black' when CSS rule is successful.</p>
<p style="color: green">This is also a test line. It is 'green' and will become 'bold' as there is no inline `font-weight` setting, but not 'black' by lack of '!important'.</p>
<p style="color: blue">This is also a test line. It is 'blue' and will not become 'black' by lack of '!important'.</p>
whlutmcx

whlutmcx2#

CSS选择器将选择任何style属性包含值“letter-spacing:1.614px”的元素和任何具有类. subjectText的后代。但是,它在您的情况下不起作用,因为style属性不是在span元素本身上定义的,而是在通用选择器上定义的。
你可以为字母间距定义一个单独的类,并将其应用于文本的父元素:

.text-spacing {
  letter-spacing: 1.641px;
}

.text-spacing > .subjectText {
  background-color: yellow;
}

相关问题