How can I style even and odd elements?

后端 未结 9 2056
离开以前
离开以前 2020-11-22 10:44

Is it possible to use CSS pseudo-classes to select even and odd instances of list items?

I\'d expect the following to produce a list of alternating colors, but inste

相关标签:
9条回答
  • 2020-11-22 11:13

    the css odd and even is not support for IE. recommend you using solution below.

    Best solution:

    li:nth-child(2n+1) { color:green; } // for odd
    li:nth-child(2n+2) { color:red; } // for even
    
    li:nth-child(1n) { color:green; }
    li:nth-child(2n) { color:red; }
    
    <ul>
      <li>list element 1</li>
      <li>list element 2</li>
      <li>list element 3</li>
      <li>list element 4</li>
    </ul>
    
    0 讨论(0)
  • 2020-11-22 11:13

    The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent. Odd and even are keywords that can be used to match child elements whose index is odd or even (the index of the first child is 1).

    this is what you want:

    <html>
        <head>
            <style>
                li { color: blue }<br>
                li:nth-child(even) { color:red }
                li:nth-child(odd) { color:green}
            </style>
        </head>
        <body>
            <ul>
                <li>ho</li>
                <li>ho</li>
                <li>ho</li>
                <li>ho</li>
                <li>ho</li>
            </ul>
        </body>
    </html>
    
    0 讨论(0)
  • 2020-11-22 11:16

    Demo: http://jsfiddle.net/thirtydot/K3TuN/1323/

    li {
        color: black;
    }
    li:nth-child(odd) {
        color: #777;
    }
    li:nth-child(even) {
        color: blue;
    }
    <ul>
        <li>ho</li>
        <li>ho</li>
        <li>ho</li>
        <li>ho</li>
        <li>ho</li>
    </ul>

    Documentation:

    • https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
    • http://caniuse.com/css-sel3 (it works almost everywhere)
    0 讨论(0)
提交回复
热议问题