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