If I have this list of elements, and I want to hide only the first one, with CSS it would be like this:
li{
background: yellow;
border: 1px solid;
margin: 10px;
display: block;
}
li:first-child {
display: none;
}
<li><a href="#">PRIMERO</a></li>
<li><a href="#">SEGUNDO</a></li>
<li><a href="#">TERCERO</a></li>
The problem occurs when the list is dynamic: it could be 0, 1, 2 or more elements, in my front I don't have how to count them.
li{
background: yellow;
border: 1px solid;
margin: 10px;
display: block;
}
li:first-child {
display: none;
}
<li><a href="#">UNICO</a></li>
How do I manage to create a CSS conditional with javascript? Only apply first:child if there is more than 1 element, otherwise the display would be block.
You could fix it the way fellow @masterguru comments. From Javascript check if the list to print has more than one element and if it does, add a class to the first one to hide it.
But if you wanted to solve it only through CSS we can take advantage of the CSS "cascade" and the pseudo-classes
first-child
andonly-of-type
.What I have done has been first to hide those
<li>
that are the first child, as you had it in your code, to then show those<li>
that also do not have any other sibling that is a<li>
.In this way the first would be hidden
<li>
only when it has other siblings<li>
, if it is alone it would not be hidden.References: cascade and inheritance , :first-child , :only-of-type