我有以下代码:
<div class="citation">
<span>some text
<span id="innerSpan">inner text</span>
some more text
</span>
</div>
Run Code Online (Sandbox Code Playgroud)
我试图用citation
类来影响div的外跨度,但不是内部跨度:
.citation {
color:red;
}
.citation span {
color: yellow
}
Run Code Online (Sandbox Code Playgroud)
我试过了:第一个类型,:nth-child,但似乎没什么用.
通过选择第一个内跨距,您将选择嵌套跨度.这使得CSS很难(或不可能)设置外部样式,span
但是inner
span继承自第二个父项.
一个解决办法是相同的样式应用.citation
和#innerSpan
,和不同风格的第一span
孩子,就像这样:
.citation,
#innerSpan {
color: red;
}
/* or you could use
/
/ .citation,
/ .citation > span > span {
/ color: red;
/ }
/
*/
.citation > span {
color: yellow;
}
Run Code Online (Sandbox Code Playgroud)
<div class="citation">
<span>some text
<span id="innerSpan">inner text</span> some more text
</span>
</div>
Run Code Online (Sandbox Code Playgroud)
绝对不理想,但有点JavaScript可以做到这一点,像这样:
var inners = Array.from(document.querySelectorAll('.citation > span > span'));
inners.forEach(inner => {
inner.style.color = window.getComputedStyle(inner.parentNode.parentNode).color;
});
Run Code Online (Sandbox Code Playgroud)
.citation {
color: red;
}
.citation > span {
color: yellow;
}
Run Code Online (Sandbox Code Playgroud)
<div class="citation">
<span>some text
<span id="innerSpan">inner text</span> some more text
</span>
</div>
Run Code Online (Sandbox Code Playgroud)