如何使用CSS第一个孩子,但不包括文本内容 [英] How to use CSS first-child but excluding text content
问题描述
这段代码并不按我期望的方式工作: data-console =truedata-babel =false>
div
< DIV> < UL> < li>< span>这是一项测试< / span>< / li> < li>以及< span>这也是一项测试< / span>< / li> < / div>
span
元素为粗体。我希望第二个不要大胆,因为它遵循纯文本And
,但我猜想:first-child
不会将文本内容视为孩子。 有没有办法区分这两种情况,并选择没有任何内容的元素或兄弟姐妹?
澄清:在我的具体情况中, code>< span> < li> 元素加粗,但只有在< li>
,并且不在任何文本或其他元素之前。
据我所知,不可以,只能使用CSS区分带有或不带兄弟文本节点的元素:
div li span:first-child {font-style:italic;} div li:first-child span {font-weight:bold;} div li:空跨度:first-child {color:red;} div li span:only-child {font-size:20px;}
< div> < UL> < li>< span>这是一项测试< / span>< / li> < li>以及< span>这也是一项测试< / span>< / li> < li>< span>另一个测试< / span>< / li> < / div>
This snippet doesn't work the way I expect:
div li span:first-child {
font-weight: bold;
}
<div>
<ul>
<li><span>This is a test</span></li>
<li>And <span>this is also a test</span></li>
</ul>
</div>
Both span
elements are bold. I would have expected the 2nd one to not be bold, because it follows the plaintext "And "
, but I guess :first-child
doesn't consider text content to be a child.
Is there a way to differentiate these two situations, and select elements which are not preceded by any content or siblings?
To clarify: In my specific case, I want to make a <span>
element in each <li>
element bold, but only if it's right at the beginning of the <li>
and not preceded by any text or other elements.
As far as I can tell, no, you cannot differentiate between elements with or without a sibling text node using CSS alone:
div li span:first-child {
font-style: italic;
}
div li:first-child span {
font-weight: bold;
}
div li:empty span:first-child {
color:red;
}
div li span:only-child {
font-size: 20px;
}
<div>
<ul>
<li><span>This is a test</span></li>
<li>And <span>this is also a test</span></li>
<li><span>another test</span></li>
</ul>
</div>
这篇关于如何使用CSS第一个孩子,但不包括文本内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!