Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css selectors nth-child - to target first (n) children

Tags:

html

css

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 ?

like image 740
Spdexter Avatar asked Jan 15 '14 14:01

Spdexter


People also ask

How do I select a specific Nth child in CSS?

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.

Which nth child () selector will target only the last list item?

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.

What is the nth child () selector used for?

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.

How do I select all 3 children in CSS?

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.


1 Answers

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

like image 148
j08691 Avatar answered Oct 24 '22 23:10

j08691