Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selector for an element with certain class, if it is the one & only child of its parent?

Tags:

html

css

I want to apply certain CSS to an element(with a certain class) if it is the one & only child within its parent. I can easily do this using jQuery but I'm looking for a pure CSS solution(that works across all major browsers). How do write selector expression for such elements ?

E.g. scenario:

<div> 
   <span class='a1'/>
</div>

<div> 
   <a>random text</a>
   <span class='a1'/>
</div>

I would like the first div contained .a1 element to be selected as it is the only element within its parent.

like image 482
Rajat Gupta Avatar asked Nov 24 '25 13:11

Rajat Gupta


1 Answers

Use .a1:only-child see this fiddle. Of course, it depends on what you consider "major browsers" as to whether it is supported or not (it is a CSS3 property).

like image 152
ScottS Avatar answered Nov 26 '25 04:11

ScottS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!