css :last-child选择器使用方法和实例分析

时间:2016-09-17
css :last-child选择器用于选择或匹配父元素的最后一个子元素,本文章向大家介绍:last-child伪类选择器的基本语法及使用实例,需要的朋友可以参考一下。

css :last-child介绍

css :last-child选择器用于选择或匹配父元素的最后一个子元素

语法:

element:last-child { style_properties }

说明:

匹配父元素的最后一个子元素element。

  • 要使该属性生效,element元素必须是某个元素的子元素,element的父元素最高是body,即E可以是body的子元素
  • element:last-child选择符,element必须是它的兄弟元素中的最后一个元素,换言之,element必须是父元素的最后一个子元素。与之类似的伪类还有element:first-child,只不过情况正好相反,需要它是第一个子元素。

css :last-child实例

设置父元素中最后一个p元素的背景色:

<!DOCTYPE html>
<html>
<head>
<title>码农教程教程(www.manongjc.com)</title> 
<style> 
p:last-child
{
background:#ff0000;
}
</style>
</head>
<body>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</body>
</html>

在线运行

提示: p:last-child等同于p:nth-last-child(1)。