Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS select first child only if two children

Is there any way to select the first child only if there is a second child? I'd like to hide the first <p></p> tag only if there is a second one. Is there any way to do this with CSS?

My code is this

<div>
    <p></p>
    <p>something</p>
</div>
like image 396
user36789 Avatar asked Aug 25 '13 17:08

user36789


2 Answers

You can only do this by combining :first-child and :nth-last-child(), which means in pure CSS you won't get any better support than IE9 and later:

p:first-child:nth-last-child(2) {
    display: none;
}

If you're looking to hide the first p when it has siblings at all (i.e. it doesn't matter whether there are 2, 3, 4... children in total), use this instead:

p:first-child:not(:only-child) {
    display: none;
}
like image 111
BoltClock Avatar answered Sep 28 '22 20:09

BoltClock


Does the solution need to be cross-browser compatible? If so, I'm not sure if it can be done with CSS. However, it's easy to accomplish with jQuery:

jsFiddle: http://jsfiddle.net/SVTxD/

$(document).ready(function(){
    $('div.myDiv').each(function(){
        console.log($(this).children().length);
        if ($(this).children('p').length > 1){
            $(this).children('p').first().hide();
        }
    });
});

Alternatively (thank you BoltClock):

$(document).ready(function(){
    $('div.myDiv p:first-child:nth-last-child(2)').hide();
});

If jQuery isn't an option (or it doesn't need to work in older browsers), then Josh C's answer is correct.

EDIT: Includedd @BoltClock's suggestion as an alternative.

like image 22
htxryan Avatar answered Sep 28 '22 21:09

htxryan