6-7 CSS3 结构性伪类选择器—last-child
本节编程练习不计算学习进度,请电脑登录imooc.com操作

CSS3 结构性伪类选择器—last-child

“:last-child”选择器与“:first-child”选择器作用类似,不同的是“:last-child”选择器选择的是元素的最后一个子元素。例如,需要改变的是列表中的最后一个“li”的背景色,就可以使用这个选择器,

ul>li:last-child{background:blue;}

示例演示

在博客的排版中,每个段落都有15px的margin-bottom,假设不想让博客“post”中最后一个段落不需要底部的margin值,可以使用“:last-child”选择器。

HTML代码:

<div class="post">
  <p>第一段落</p>
  <p>第二段落</p>
  <p>第三段落</p>
  <p>第四段落</p>
  <p>第五段落</p>
</div>​

CSS代码:

.post {
  padding: 10px;
  border: 1px solid #ccc;
  width: 200px;
  margin: 20px auto;
}
.post p {
  margin:0 0 15px 0;
}

.post p:last-child {
  margin-bottom:0;
}

演示结果:

 

任务

在CSS编辑器的第十四行输入正确的代码,删除列表中最后一个列表项的底部边框。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>结构伪类选择器——last-child</title>
  6. <link href="style.css" rel="stylesheet" type="text/css">
  7. </head>
  8. <body>
  9. <ul>
  10. <li>Item1</li>
  11. <li>Item2</li>
  12. <li>Item3</li>
  13. <li>Item5</li>
  14. <li>Item6</li>
  15. </ul>
  16. </body>
  17. </html>
  1. ul {
  2. border: 1px solid #ccc;
  3. list-style: none outside none;
  4. width: 220px;
  5. margin: 20px auto;
  6. padding: 0;
  7. }
  8. ul > li {
  9. list-style: none outside none;
  10. margin:0;
  11. padding: 10px;
  12. border-bottom: 3px solid #ccc;
  13. }
  14. ul > li? {
  15. border-bottom: none;
  16. }
下一节