如何设置偶数和奇数元素的样式? [英] How can I style even and odd elements?

查看:119
本文介绍了如何设置偶数和奇数元素的样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用CSS伪类选择列表项的偶数和奇数实例?

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 instead I get a list of blue items:

<html>
    <head>
        <style>
            li { color: blue }
            li:odd { color:green }
            li:even { color:red }
        </style>
    </head>
    <body>
        <ul>
            <li>ho</li>
            <li>ho</li>
            <li>ho</li>
            <li>ho</li>
            <li>ho</li>
        </ul>
    </body>
</html>

推荐答案

演示: 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>

文档:

  • https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
  • http://caniuse.com/css-sel3 (it works almost everywhere)

这篇关于如何设置偶数和奇数元素的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆