CSS select the first child only if two children

Is there a way to choose the first child only if there is a second child? I would like to hide the first <p></p> only if there is a second. Is there a way to do this using CSS?

My code is

 <div> <p></p> <p>something</p> </div> 
+4
source share
2 answers

You can do this by combining :first-child and :nth-last-child() , which means that in pure CSS you will not get better support than IE9 and later:

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

If you want to hide the first p when it has brothers and sisters (i.e. it doesn't matter if there are only 2, 3, 4 ... children), use this instead:

 p:first-child:not(:only-child) { display: none; } 
+10
source

Is a cross browser solution required? If so, I'm not sure if this can be done using CSS. However, this is 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 (thanks to BoltClock):

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

If jQuery is not a parameter (or it does not need to work in older browsers), then the correct answer is Josh C.

EDIT: Alternatively, the AddB @BoltClock clause is included.

0
source

Source: https://habr.com/ru/post/1498852/


All Articles