I have been trying to target only the first four list items in the using css selector nth-child and/or nth-last-child
<ul>
<li>Hello first item</li>
<li>Hello item 2<li>
<li>Hello item 3</li>
<li>Hello item 4</li>
<li>Hello item 5</li>
<li>Hello item 6</li>
<li>Hello item 7</li>
<li>Hello item 8</li>
<li>Hello item 9</li>
</ul>
my first try:
ul li:nth-child(1n):not(:nth-last-child(-n+5)){
font-weight:bold;
}
Yet i wanted to simplify it
so my second one:
ul li:nth-child(-n+4){
font-weight:bold;
}
Can you tell me if there is any better solution than second one / is this the right way to target first (n) children ?
The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
The :nth-last-child(n) selector matches every element that is the nth child, regardless of type, of its parent, counting from the last child. n can be a number, a keyword, or a formula.
The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.
formula (an + b) In addition to the value n being able to be any number, you can also use a formula. nth-child(3n) would affect every third child element. nth-child(3n+1) would apply to every third element starting from the first one.
Your code works if you fix the typo:
jsFiddle example
Although a better solution may be:
ul li:nth-child(-n+4) {
font-weight:bold;
}
jsFiddle example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With