CSS 中使用 :even 和 :odd 伪类选择列表项
CSS 的 :even 和 :odd 伪类用于选择或定位交替的子元素。 CSS 的偶数和奇数伪类与列表项一起使用,可以创建交替的样式,例如文本颜色、背景颜色,从而提高可读性。
在本文中,我们有一个 无序列表。我们将了解 :even 和 :odd 伪类在列表项中的用法。
CSS 奇数伪类
:odd 伪类用于选择位于奇数位置的 HTML 元素。我们可以将 :odd 类与 nth-child() 或 :nth-of-type() 伪类选择器一起使用,以选择列表中所有位于奇数位置的子元素。
示例
在本例中,我们使用了 ol 和 li 标签来创建一个无序列表。我们使用 :odd 伪类来选择位于奇数位置的列表项并更改其文本 颜色。
<html>
<head>
<style>
li:nth-child(odd) {
color: #04af2f;
}
</style>
</head>
<body>
<h3>CSS :odd psuedo-class Example</h3>
<p>
In this example, we have used <strong>odd</strong>
pseudo-class to change the color of odd list items.
</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
</ul>
</body>
</html>
注意:我们也可以使用 2n+1 作为参数来选择奇数列表项。
CSS 偶数伪类
:even 伪类用于选择位于偶数位置的 HTML 元素。我们可以将 :even 类与 nth-child() 或 :nth-of-type() 伪类选择器一起使用,以选择列表中所有位于偶数位置的子元素。
示例
在本例中,我们使用了 :even 伪类来选择位于偶数位置的列表项并更改其文本颜色。
<html>
<head>
<style>
li:nth-child(even) {
color: #1af0d0;
}
</style>
</head>
<body>
<h3>CSS :even psuedo-class Example</h3>
<p>
In this example, we have used <strong>even</strong>
pseudo-class to change the color of even list items.
</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
</ul>
</body>
</html>
注意:我们也可以使用 2n 作为参数来选择偶数列表项。
示例 2
在本例中,我们使用了 :odd 和 :even 伪类来更改列表项的交替文本颜色。
<html>
<head>
<style>
li {
max-width: fit-content;
}
li:nth-child(odd) {
color: #04af2f;
}
li:nth-child(even) {
color: #1af0d0;
}
</style>
</head>
<body>
<h3>CSS :odd and :even psuedo-class Example</h3>
<p>
In this example, we have used <strong>odd</strong>
and <strong>even</strong> pseudo-class to change
the color of alternate list items.
</p>
<ul>
<li>Odd</li>
<li>Even</li>
<li>Odd</li>
<li>Even</li>
<li>Odd</li>
<li>Even</li>
<li>Odd</li>
<li>Even</li>
<li>Odd</li>
</ul>
</body>
</html>
结论
在本文中,我们学习并理解了 CSS 中 :even 和 :odd 伪类在列表项中的用法。我们使用 even 和 odd 作为 nth-child 或 nth-of-type 中的参数,因为它们不是独立的伪类。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP