1. html 结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>nth Child</title>
</head>
<body>
<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>
<li>Item 10</li>
<li>Item 11</li>
<li>Item 12</li>
<li>Item 13</li>
<li>Item 14</li>
<li>Item 15</li>
<li>Item 16</li>
<li>Item 17</li>
<li>Item 18</li>
<li>Item 19</li>
<li>Item 20</li>
</ul>
</body>
</html>
2. css 样式
li {
padding: 0.25rem;
margin: 0.25rem;
list-style: none;
}
/* 选择父元素的第一个子元素 */
li:first-child {
background-color: red;
}
/* 选择父元素的最后一个子元素 */
li:last-child {
background-color: red;
}
/* 选择第三个 */
li:nth-child(3) {
background-color: blueviolet !important;
}
/* 选择3的倍数 */
li:nth-child(3n) {
background-color: olive;
}
/* 从7开始,按3的倍数进行选择 */
li:nth-child(3n+7) {
background-color: aqua;
}
li:nth-child(odd) {
background-color: violet;
}
li:nth-child(even) {
background-color: black;
}