
0001.jpg
子代类型选择符与子代选择符的作用很相似,不过子代类型选择符用于选取特定类型子代HTML标签。
:first-of-type
这个选择符的作用与:first-child类似,不过选取的是首次出现的特定类型的子代标签。假如侧边栏的类为sidebar,若想为侧边栏里的第一个段落定义样式,可以使用下面的方法:
HTML代码
<div class="sidebar">
<h1>侧边栏</h1>
<p>段落文本1</p>
<p>段落文本2</p>
<p>段落文本3</p>
</div>
CSS代码
.sidebar p:first-of-type {
font-weight: bold;
color: orange;
}

image.png
:last-of-type
:last-of-type的作用与:last-child类似,不过选取的是最后一个特定类型的子代标签。比如想设定类为sidebar这个侧边栏的最后一个段落的样式。
HTML代码
<div class="sidebar">
<h1>侧边栏</h1>
<p>段落文本1</p>
<p>段落文本2</p>
<p>段落文本3</p>
</div>
CSS代码
.sidebar p:last-of-type {
font-weight: bold;
color: orange;
}

image.png
:nth-of-type
这个选择符的作用与:nth-child()类似,不过选取的是相隔的特定类型的子代标签。
如果一大段文字中间掺杂着一些图片,此时就体现出这个选择符的作用了。
例如
HTML代码
<p>
黑麦面包看起来沉甸甸的,质地相当扎实。
<img src="images/timg1.jpg" alt="">...内容...
<img src="images/timg2.jpg" alt="">...内容...
<img src="images/timg3.jpg" alt="">...内容...
<img src="images/timg4.jpg" alt="">...内容...
不能过于清单而输给面包风味。
</p>
CSS代码
img:nth-of-type(odd) {
float:left;
}
img:nth-of-type(even){
float:right;
}

image.png
:nth-of-type 和 :nth-child() 一样,都可以使用关键字(odd或even)和公式。
希望以上笔记对大家有帮助。
我的其他笔记在微信公众号:Rabbit_svip
欢迎前来点评~

qrcode_for_gh_6c5c0ec5e65b_258.jpg