How to select first 2 <li> elements using css

Css

Css Problem Overview


Hi i want to apply css for first 2 elements (one,two) that are adjacent to first <p> element.

<div class="one">
    <ul>
        <p>
            <li>One</li>
            <li>Two</li>
        <p>
        <li>Four</li>
        <li>Five</li>
    </ul>
</div>

Following getting applied to all 4 li elements

.one ul p:nth-child(odd) ~ li {
    background: lightsteelblue;
}
   

Css Solutions


Solution 1 - Css

For first 2 li elements inside ul p try:

.one ul li:nth-child(-n+3){
    // your style
}

See on jsfiddle

And as other mates mentioned: you have invalid markup.

If you removed p element, try:

.one ul li:nth-child(-n+2){
    // your style
}

See on jsfiddle

Update: My suggestion is to use another ul instead of p: So you have valid markup and same result:

HTML

<div class="one">
    <ul>
        <li>0</li>
        <li>
            <ul>
                <li>One</li>
                <li>Two</li>
                <li>3</li>
            </ul>
        <li>
        <li>Four</li>
        <li>Five</li>
    </ul>
</div>

CSS:

.one ul {
    padding: 0;
    list-style-type: none;
}
.one ul ul li:nth-child(-n+2){
    // your style
}

Updated jsfiddle

Note: As your last comment, If you have only 2 special li element, Why not define a class name simply... <li class="bold"> Do it simple

ul li.bold {
    // your style
}

Solution 2 - Css

This should be compatible with IE8 (uses CSS 2.1 selectors only):

li:first-child, li:first-child+li {
    color: blue;
}

Solution 3 - Css

First three elements you can select with e.g.

ul li:nth-of-type(-n+3) {

}

But like others mentioned, your markup is invalid and you should definitely correct it.

Solution 4 - Css

Like others already mentioned, the straightforward answer would be li:nth-child(-n+2) { ... }.

I don't know about you, but when I first learn this -n+2 part, my reaction was "what? is this a typo?". So, for those who like to know a little explanation rather than just copy-and-paste the counter-intuitive magic, here I include a link to a wonderful blog post by Sara Cope explaining the -n+2 part:

> The syntax for selecting the first n number of elements is a bit counter-intuitive. You start with -n, plus the positive number of elements you want to select. For example, li:nth-child(-n+2) will select the first 2 li elements.

Such explanation is even missing in the w3cshool for nth-child.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrajeshView Question on Stackoverflow
Solution 1 - CssVahid HallajiView Answer on Stackoverflow
Solution 2 - CssNathan J.B.View Answer on Stackoverflow
Solution 3 - CssmkasView Answer on Stackoverflow
Solution 4 - CssRayLuoView Answer on Stackoverflow