目录
所有选择器
选择器 | 用法 |
---|---|
id选择器 | #myid |
类选择器 | .myclassname |
标签选择器 | div,h1,p |
相邻选择器 | h1+p |
子选择器 | ul > li |
后代选择器 | li a |
通配符选择器 | * |
属性选择器 | a[rel=“external”] |
伪类选择器 | a:hover, li:nth-child |
伪类选择器
定义:结构伪类选择器主要根据的是文档的结构来选择元素,常常用在根据父级选择器选出某些想要的子元素。
主要语法如下:
编号 | 语法 | 含义 |
---|---|---|
1 | E:first-child | 匹配父元素中的第一个子元素E |
2 | E:last-child | 匹配父元素中最后一个E元素 |
3 | E:nth-child(n) | 匹配父元素中的第n个子元素E |
4 | E:first-of-type | 指定类型E的第一个 |
5 | E:last-of-type | 指定类型E的最后一个 |
6 | E:nth-of-type(n) | 指定类型E的第n个 |
区别(:nth-child(n) 和 :nth-of-type(n))
示例:
<div id="parent">
<p>Paragraph 1</p>
<div>Div 1</div>
<p>Paragraph 2</p>
<div>Div 2</div>
<p>Paragraph 3</p>
</div>
/* 使用 :nth-child(n) */
#parent > *:nth-child(2) {
color: red;
}
/* 使用 :nth-of-type(n) */
#parent > p:nth-of-type(2) {
color: blue;
}