如何设置偶数和奇数元素的样式?

HTML CSS

Mandy猿

2020-03-24

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

我希望以下内容会产生一系列交替的颜色,但我会得到蓝色项目的列表:

<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>

第3232篇《如何设置偶数和奇数元素的样式?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

8个回答
十三小卤蛋 2020.03.24

但它在IE中不起作用。建议使用:nth-​​child(2n + 1):nth-​​child(2n + 2)

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>

乐米亚 2020.03.24

:nth-​​child(n)选择器匹配作为父元素的第n个子元素的每个元素(无论类型如何)。奇数和偶数是关键字,可用于匹配索引为奇数或偶数(第一个孩子的索引为1)的子元素。

这就是你想要的:

<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>
米亚米亚小卤蛋 2020.03.24

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>

在此处查看浏览器支持: CSS3:nth-​​child()选择器

前端古一 2020.03.24

CSS的问题在于伪类的语法。

偶数和奇数伪类应为:

li:nth-child(even) {
    color:green;
}

li:nth-child(odd) {
    color:red;
}

演示:http//jsfiddle.net/q76qS/5/

小宇宙泡芙 2020.03.24

CSS的奇数和偶数不支持IE。建议您使用下面的解决方案。

最佳解决方案:

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>
蛋蛋猿 2020.03.24

用这个:

li { color:blue; }
li:nth-child(odd) { color:green; }
li:nth-child(even) { color:red; }

有关浏览器支持的信息,请参见此处:http : //kimblim.dk/css-tests/selectors/

小胖 2020.03.24

以下是适用于偶数和奇数css颜色的示例

<html>
<head>
<style> 
p:nth-child(even) {
    background: red;
}
p:nth-child(odd) {
    background: green;
}
</style>
</head>
<body>

<p>The first Odd.</p>
<p>The second Even.</p>
<p>The third Odd.</p>
<p>The fourth Even.</p>


</body>
</html>
2020.03.24

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

说明文件:

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android