<div><p> My paragraph here. </p></div><div> <p> Two paragraphs total. </p> <p> Two paragraphs total. </p></div>
兼容 IE9+
29.
X:only-of-type
li:only-of-type { font-weight: bold;}
这个选择器会选取某个元素,并且这个元素在其父层内没有其他同级同类元素(不一定是唯一元素)。比如,要选取所有只包含一个 li 元素的 ul 元素该怎么做呢?如果使用
ul li 将选取所有 li 元素,应该使用
only-of-type。兼容 IE9+
30.
X:first-of-type
first-of-type 伪类可以选取某种元素的第一个同类元素。为了更好地理解它的用法,现在思考一下如何在下面的 HTML 结构中选取
List Item 2 ?<div> <p> My paragraph here. </p> <ul> <li> List Item 1 </li> <li> List Item 2 </li> </ul> <ul> <li> List Item 3 </li> <li> List Item 4 </li> </ul></div>
方法一
ul:first-of-type > li:nth-child(2) { font-weight: bold;}
这段代码的意思是:首先选取第一个 ul 元素;然后选取其中的所有直接子元素,也就是 li;最后选取第二个子元素。
方法二
p + ul li:last-child { font-weight: bold;}
找到 p 元素后第一个出现的 ul 元素,然后选取其中的最后一个子元素。
方法三
ul:first-of-type li:nth-last-child(1) { font-weight: bold;}
找到第一个 ul 元素,然后从上往下选取第一个子元素。
兼容 IE9+
31. 伪类选择器叠用
有些伪类选择器或者伪元素是可以叠用的,例如:
#post p:nth-of-type(2):first-letter { float: left; margin: 0 5px 0 1em; width: 1em; height: 1em; font-size: 2em;}
目测兼容 IE9+,听说 IE10 有个小 bug










