The CSS pseudo-class :nth-of-type()
selects elements based on their position relative to siblings of the same type (tag name). For more information, check out the documentation.
If you want to hide the second li
element, using this pseudo-class won't be helpful.
One approach involves two steps:
- Hide all instances of a specific selector
- Show those that come after a matching sibling (the
~
denotes "sibling of" - refer to the docs)
/* Hide all li.cart_item.subtotal and li.cart_item.delivery_fee */
li.cart_item.subtotal,
li.cart_item.delivery_fee {
display: none;
}
/* Show ones with a preceding sibling of the same classes */
li.cart_item.subtotal ~ li.cart_item.subtotal,
li.cart_item.delivery_fee ~ li.cart_item.delivery_fee {
display: list-item;
}
<ul class="cart not-empty-cart">
<li class="cart_item" data-cart-key="0">aaaaa</li>
<li class="cart_item subtotal">bbbb</li>
<li class="cart_item delivery_fee">cccc</li>
<li class="cart_item subtotal">dddd</li>
<li class="cart_item delivery_fee">eeee</li>
<li class="cart_item total">fff</li>
<li class="cart_item checkout">gggg</li>
</ul>
Another user previously suggested a more concise method involving combining these two steps:
- Select elements to hide that do not have a preceding sibling matching the selector
/*
* Hide all li.cart_item.subtotal and li.cart_item.delivery_fee
* if they don't come after a matching sibling.
*/
li.cart_item.subtotal:not(li.cart_item.subtotal ~ *),
li.cart_item.delivery_fee:not(li.cart_item.delivery_fee ~ *) {
display: none;
}
<ul class="cart not-empty-cart">
<li class="cart_item" data-cart-key="0">aaaaa</li>
<li class="cart_item subtotal">bbbb</li>
<li class="cart_item delivery_fee">cccc</li>
<li class="cart_item subtotal">dddd</li>
<li class="cart_item delivery_fee">eeee</li>
<li class="cart_item total">fff</li>
<li class="cart_item checkout">gggg</li>
</ul>
In CSS Level 4 selectors, there is the :nth-child(x of y) option, however, it currently lacks widespread browser support.
/* Limited browser compatibility, may work in Safari */
:nth-child(1 of .cart_item.subtotal) {
display: none;
}