相对于父元素的伪类
-
E:first-child
:查找相对于E的父元素
的第一个指定类型
的子元素
-
E:last-child
:查找相对于E的父元素
的最后一个指定类型
的子元素
-
E:first-of-type
:返回该类型的第一个
-
E:last-of-type
:返回该类型的最后一个
-
E:nth-child(n)
:返回该类型的第n个,n从1开始索引,n小于0则不生效
- 若要取前5个E,E:nth-child(-n+5)
E:nth-child(-n+5){
color:#ccc;
}
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
ul {
width: 700px;
height: 500px;
margin: 200px auto;
border-left: 1px solid #000;
border-top: 1px solid #000;
}
ul li {
float: left;
list-style: none;
width: 100px;
height: 100px;
box-sizing: border-box;
line-height: 100px;
text-align: center;
border-right: 1px solid #000;
border-bottom: 1px solid #000;
}
li:first-child {
color: #1fe;
}
li:last-child{
background-color: #1fe;
}
li:first-of-type{
background-color: #453ea3;
}
li:last-of-type{
color: #fff;
}
li:nth-child(5){
background-color: red;
}
li:nth-of-type(5){
color: #0f0;
}
li:nth-last-of-type(5){
font-size: 20px;
}
li:empty{
background-color: black;
}
li:nth-last-child(-n+9){
color: skyblue;
}
li:nth-last-of-type(odd){
background-color: pink;
}
li:nth-last-of-type(even){
background-color: gold;
}
</style>
</head>
<body>
<ul>
<div></div>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
<li>13</li>
<li>14</li>
<li>15</li>
<li>16</li>
<li>17</li>
<li>18</li>
<li>19</li>
<li></li>
<li>21</li>
<li>22</li>
<li>23</li>
<li>24</li>
<li></li>
<li>26</li>
<li>27</li>
<li>28</li>
<li>29</li>
<li>30</li>
<li>31</li>
<li>32</li>
<li>33</li>
<li>34</li>
<li>35</li>
</ul>
</body>
</html>