:nth-of-type(n) 的作用不是选取子元素 (child element),而是选取同类元素 (type of element)。想象一下 HTML 文件中包含 5 个 ul 元素,现在要选取第三个,只需使用上面的代码,而不用再单独这个 ul 添加
id。关于
与:nth-child的区别,具体请查看 CSS-Tricks 网站的解释,简单来说,如果父层内只包含一种元素(比如都是 p 元素)那两种用法是等效的,如果父层包含多种元素(比如 p 元素与同级的其他元素),需要选取第几个 p 元素时应该用:nth-of-type。:nth-of-type
兼容 IE9+
25.
X:nth-last-of-type(n)
ul:nth-last-of-type(3) { border: 1px solid black;}
与第 24 条用法相同,倒序选取同类元素。
兼容 IE9+
26.
X:first-child
ul li:first-child { border-top: none;}
选取父层内的第一个子元素。
兼容 IE7+
27.
X:last-child
ul > li:last-child { color: green;}
与第 26 条用法相同,区别在于
:last-child 选取父层元素内的最后一个子元素。
:first-child 与
:last-child 通常用来清除边框 (border),比如
<ul></ul> 内每个
<li></li> 都使用了
border-top 与
border-bottom 边框,结果是,第一个元素的上方与最后一个元素的下方会是单边框效果。这种情况可以用
:first-child 与
:last-child 清除上下的边框,而不用给第一个元素添加
id="first" 或者给最后一个元素添加
id="last"。兼容 IE9+
28.
X:only-child
div p:only-child { color: red;}
这个伪类选择器不常用,它可以选取包含唯一指定子元素的父层。比如上面的代码中将选取下面第一个 div 元素,而不是第二个 div 中的 p 元素。










