Rajat Gupta
Rajat Gupta

Reputation: 26597

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

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.

Upvotes: 3

Views: 70

Answers (2)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try this for Cross browser compatibility,

.a1:first-child:last-child {
     color :red;
}

DEMO

Upvotes: 2

ScottS
ScottS

Reputation: 72261

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).

Upvotes: 2

Related Questions