Question

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>
Was it helpful?

Solution

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.

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top