Aggelos Sfakianos
Aggelos Sfakianos

Reputation: 157

Nth-child() selector alternative solution in CSS

So we want to access -n+3 li elements in a list (if there are different types of elements before the li elements we want to access is a detail we do not care about) and I used the following way:

<html>
    <body>

        <style>
            li:nth-child(-n+3) {
                background: #ff0000;
            }
        </style>

        <p>An unordered list:</p>

        <ul>
            <h1>heading</h1>
            <li>coffee</li>
            <li>tea</li>
            <li>water</li>
            <li>coca-cola</li>
            <li>sprite</li>
            <li>orange juice</li>
            <li>beer</li>
        </ul>

    </body>
</html>

And it works fine, however in Explorer 8 and earlier versions, nth-child() selector is not supported. So how can we access the -n+3 li elements without using the pseudo class nth-child()?

Upvotes: 3

Views: 7670

Answers (1)

Harry
Harry

Reputation: 89750

You can use the :first-child and adjacent sibling selector. They work from IE7+.

Notes:

  • You shouldn't be using h1 tag as a direct child of any ul. But if that's how your structure is and you can't modify it then you can use :first-child + li, :first-child + li + li.
  • :nth-child(-n+3) generally would select the first 3 children of a parent. In your demo, since the first child is a h1 and since you've also attached the element type (li) to the nth-child(-n+3) the h1 doesn't get selected and only the two li that follow it are selected. The selector that I've mentioned in Note 1 will do the same (that is, it will select the first two li that follow the first child - which is, the h1 tag - irrespective of how many children the ul has).

Demo 1: (without any other tag directly inside ul)

li:first-child,
li:first-child + li {
  color: red;
}
<ul>
  <li>first</li>
  <li>second</li>
  <li>third</li>
  <li>fourth</li>
  <li>and so on..</li>
</ul>

Demo 2: (with your structure)

ul :first-child + li,
ul :first-child + li + li {
  color: red;
}

li:nth-child(-n+3){
  background: beige;
}
<p>An unordered list:</p>
<ul>
  <h1>heading</h1>
  <li>coffee</li>
  <li>tea</li>
  <li>water</li>
  <li>coca-cola</li>
  <li>sprite</li>
  <li>orange juice</li>
  <li>beer</li>
</ul>

Upvotes: 8

Related Questions