没有匹配的一般兄弟的CSS规则 [英] CSS rule for no matching general sibling
问题描述
如果我想只在有一个 p
兄弟姐妹的情况下对 div
CSS规则:
If I want to style a div
element only when there is a p
sibling, I can write the following CSS rule:
p ~ div
有不匹配的兄弟姐妹吗?
例如:
p !~ div
<section>
<p></p>
<div></div>
<div></div>
</section>
<section>
<div></div> <!-- Style this one -->
<div></div> <!-- Style this one -->
</section>
推荐答案
如果:not
允许的组合器,你可以简单地做 div:not(p〜div)
。但它不会,所以你不能以这种方式使用:not()
。
If :not()
allowed combinators, you would be able to simply do div:not(p ~ div)
. But it doesn't, so you won't be able to use :not()
in that manner.
您需要的选择器将取决于您的结构。在您的情况下,如果没有 p
导致第一个 div
成为您的 section
,您可以使用 div:first-child
确保您选择 div
s如果且仅当满足该条件:
The selector you need will depend on your structure. In your case, if not having the p
causes the first div
to be the first child of your section
, you can use div:first-child
to make sure you select your div
s if and only if that condition is met:
div:first-child, div:first-child ~ div
如果你的结构不允许这样的选择器被构造,那么你将不得不依赖于一个重写Danield建议的规则。
If your structure does not allow such a selector to be constructed, then you will have to rely on an overriding rule as Danield suggests.
这篇关于没有匹配的一般兄弟的CSS规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!