学习笔记,仅供参考,有错必究

参考自:pink老师教案



结构伪类选择器



属性列表:

CSS基础(part20)--CSS3结构伪类选择器_示例代码



​nth-child(n)​​ 参数详解:

  • 注意:本质上就是选中第几个子元素
  • ​n​​可以是数字、关键字、公式
  • ​n​​如果是数字,就是选中第几个
  • 常见的关键字有​​even​​ 偶数、​​odd​​ 奇数
  • 如果是第0个元素,或者超出了元素的个数会被忽略


​nth-child​​​ 和 ​​nt-of-type​​ 的区别:

  • ​nth-child​​ 选择父元素里面的第几个子元素,不管是何种类型
  • ​nt-of-type​​ 选择指定类型的元素


  • 举个例子


示例代码1:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>结构伪类选择器</title>
<style>
ul li:first-child {
background-color: pink;
}

ul li:last-child {
background-color: deeppink;
}
/* nth-child(n) 我们要第几个,n就是几 比如我们选第8个, 我们直接写 8就可以了 */

ul li:nth-child(5) {
background-color: blue;
}
</style>
</head>

<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
</ul>
</body>

</html>



页面:
CSS基础(part20)--CSS3结构伪类选择器_伪类选择器_02



示例代码2:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>结构伪类选择器</title>
<style>
/* even 是偶数 odd 是奇数 */

ul li:nth-child(odd) {
background-color: pink;
}
/* 2n 偶数 类似于 even */

ul li:nth-child(2n) {
background-color: blue;
}
</style>
</head>

<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
</ul>
</body>

</html>

页面:

CSS基础(part20)--CSS3结构伪类选择器_html_03



示例代码3:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>结构伪类选择器</title>
<style>
div span:nth-child(3) {
background-color: pink;
}
/* of-type 选择指定类型的元素 */

div span:first-of-type {
background-color: purple;
}

div span:last-of-type {
background-color: skyblue;
}

div span:nth-of-type(3) {
background-color: red;
}
</style>
</head>

<body>
<div>
<p>我p标签</p>
<span>我是span1</span>
<span>我是span2</span>
<span>我是span3</span>
<span>我是span4</span>
</div>

</body>

</html>

页面:

CSS基础(part20)--CSS3结构伪类选择器_伪类选择器_04