模式的力量:使用 nth-child
本课属于 Coddy HTML 学习旅程的“精通 CSS”单元。第 15 课,共 43 课。
:nth-child() 伪类根据元素在父元素中的顺序进行选择,并使用数字或模式来决定选择哪些元素。
例如,我们有一个列表:
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
<li>Fifth item</li>
</ul>我们这样选择序号为偶数的列表项:
li:nth-child(even) {
background-color: lightblue;
}我们这样选择第 3 个项目:
li:nth-child(3) {
font-weight: bold;
}我们可以这样选择每 5 个项目中的第 5 个:
li:nth-child(5n) {
color: red;
}挑战
简单创建一条 CSS 规则,使用 :nth-child() 为每第三个 <div> 设置黄色背景。
亲手试试
<!DOCTYPE html>
<html>
<head>
<title>Pattern Power: Using nth-child</title>
<style>
/* Write your CSS rule here */
</style>
</head>
<body>
<div class="container">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div>Item 5</div>
<div>Item 6</div>
<div>Item 7</div>
<div>Item 8</div>
<div>Item 9</div>
<div>Item 10</div>
</div>
</body>
</html>这节课包含一个小测验。开始学习即可作答,并记录你的进度。
精通 CSS中的所有课
自己练习: Web 在线编辑器