nth-of-type等相對於父元素的結構偽類
阿新 • • 發佈:2018-12-13
相對於父元素的偽類
-
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; } /* n = 0; 5 n = 1; 4 ... n >= 5; 0 不生效 */
程式碼
<!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;
}
/*
相對於父元素的結構偽類:
E:first-child:查詢E元素的父級元素中的第一個E元素,
1.相對於當前元素的的父級元素;
2.查詢型別必須是指定型別,
如果查詢到的第一個元素不是指定元素,則樣式不會生效
*/
li:first-child {
color: #1fe;
}
/*
E:last-child:查詢E元素的父級元素中的最後一個E元素;如果最後一個元素不是E則不生效;
*/
li:last-child{
background-color: #1fe;
}
/*
查詢的時候限制類型:first-of-type
1.相對於父元素進行查詢
2.在查詢的時候指揮查詢指定型別的元素,過濾其他型別的元素;
*/
li:first-of-type{
background-color: #453ea3;
}
/* 最後一個li元素 */
li:last-of-type{
color: #fff;
}
/*
E:nth-child(n):查詢E的父級元素中的第n個,不限制查詢型別,只會找到父元素的第n個子元素。
*/
li:nth-child(5){
background-color: red;
}
/*
E:nth-of-type(n):查詢E的父級元素中的第n個,限制查詢型別,只會找到父元素的第n個E元素。
*/
li:nth-of-type(5){
color: #0f0;
}
/*
E:nth-last-of-type(n):從最後開始查詢第n個
*/
li:nth-last-of-type(5){
font-size: 20px;
}
/*
E:empty:查詢內容為空的E元素,
*/
li:empty{
background-color: black;
}
/*
1.of-type限制類型
2.n可以是奇數(odd)和偶數(even)
*/
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>