Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css target child class if single

Tags:

css

I got following markup:

<div>
<p class="active"></p>
<p></p>
<p class="active"></p>
<p></p>
</div>

At one point I get this markup:

<div>
<p></p>
<p></p>
<p class="active"></p>
<p></p>
</div>

Now I want to style the active class, but only if there is only one active class within the div. If there are more than one active class their should be different styling. Something like:

div .active{
color: red;
}

div .active:only-child{
color:green;
}

If there a way achieving this without js? Only CSS?

like image 796
Jonny Vince Avatar asked Oct 19 '22 01:10

Jonny Vince


2 Answers

No, you can't achieve that in plain CSS since you can't access a parent element from a specific selector, nor can you style an element based on whether it has a child with specific class name.

You can add a helper class name to the parent element. Something like .has-active-items.

like image 199
feeela Avatar answered Oct 21 '22 22:10

feeela


Until the nth-match css selector is implemented in major browsers (give it a few years, hah) this is not possible with pure CSS as far as I know.

Similar discussion over at CSS3 selector :first-of-type with class name?

Sorry!

like image 45
CollinD Avatar answered Oct 21 '22 23:10

CollinD