同學們遇到過給同一組元素的最後一個元素設置css失效的情況嗎?我遇到過,當時使用:last-child居然不起作用,看到名字不科學啊,明明是“最後一個元素”,那爲什麼設置CSS失效呢?今天來一探究竟吧
- 先看一組
:last-child
正常工作的代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>:last-child、:last-of-type</title>
<script src="../../lib/jquery-2.1.0.js"></script>
<style>
ul {
margin: 100px 0;
}
li {
list-style: circle;
border-bottom: 1px solid #000000;
}
li:last-child {
border-color: red;
}
</style>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<!--<p>我是來騷擾的</p>-->
</ul>
</body>
</html>
- 再先看一組
:last-child
不正常工作的代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>:last-child、:last-of-type</title>
<script src="../../lib/jquery-2.1.0.js"></script>
<style>
ul {
margin: 100px 0;
}
li {
list-style: circle;
border-bottom: 1px solid #000000;
}
li:last-child {
border-color: red;
}
</style>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<p>我是來騷擾的</p>
</ul>
</body>
</html>
問題拋出來了,那麼來研究下:last-child和:last-of-type究竟是何方神聖。
-
:last-child:The last-child CSS pseudo-class represents the last element among a group of sibling elements.(:last-child這個css僞類代表的一組兄弟元素當中最後一個元素)但經過代碼發現,它說的一組元素應該是指其父元素的所有子元素且類型爲:last-child前面指定的類型的一組元素。
-
:last-of-type:The last-of-type CSS pseudo-class represents the last element of its type among a group of sibling elements.(:last-of-type這個css僞類代表其類型的一組兄弟元素中的最後一個元素**)所以它指的是和**:last-of-type前面的元素類型一致的一組元素的最後一個元素
同理::nth-last-child和:nth-last-of-type的區別在於父元素的子元素中且與:nth-last-child前面的元素類型一致的最後一個元素
做個驗證
- :nth-last-child可以正常工作的代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>:last-child、:last-of-type</title>
<script src="../../lib/jquery-2.1.0.js"></script>
<style>
ul {
margin: 100px 0;
}
li {
list-style: circle;
border-bottom: 1px solid #000000;
}
li:nth-last-child(1){
border-color: red;
}
</style>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<!--<p>我是來騷擾的</p>-->
</ul>
</body>
</html>
- :nth-last-child不能正常工作的代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>:last-child、:last-of-type</title>
<script src="../../lib/jquery-2.1.0.js"></script>
<style>
ul {
margin: 100px 0;
}
li {
list-style: circle;
border-bottom: 1px solid #000000;
}
li:nth-last-child(1){
border-color: red;
}
</style>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<p>我是來騷擾的</p>
</ul>
</body>
</html>
- 接下來:nth-last-of-type閃亮登場
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>:last-child、:last-of-type</title>
<script src="../../lib/jquery-2.1.0.js"></script>
<style>
ul {
margin: 100px 0;
}
li {
list-style: circle;
border-bottom: 1px solid #000000;
}
li:nth-last-of-type(1){
border-color: red;
}
</style>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<p>我是來騷擾的</p>
</ul>
</body>
</html>