CSS rule for no matching general sibling

三世轮回 提交于 2019-12-11 13:32:28

问题


If I want to style a div element only when there is a p sibling, I can write the following CSS rule:

p ~ div

Is there a CSS rule for styling an element when there isn't a matching sibling?

For example something like:

p !~ div

<section>
   <p></p>
   <div></div>
   <div></div>
</section>
<section>
   <div></div> <!-- Style this one -->
   <div></div> <!-- Style this one -->
</section>

回答1:


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.

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 divs if and only if that condition is met:

div:first-child, div:first-child ~ div

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.




回答2:


How about doing it the other way around:

Set a style for all the divs according to the way you want them when no <p> elements are there.

Then override that style when there is a <p> element.

section div
{
    color: green;
}

section p ~ div
{
    color: black;
}

FIDDLE




回答3:


Just give id/class to div and write its corresponding CSS simple



来源:https://stackoverflow.com/questions/22660995/css-rule-for-no-matching-general-sibling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!