伪类语法

selector:pseudo-class {property:value;}

常见伪类

a标签上的伪类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*未访问的链接*/
a:link{

}
/*已访问的链接*/
a:visited{

}
/*鼠标滑过的链接*/
a:hover{

}
/*已选中(鼠标按下)的链接*/
a:active{

}

在CSS定义中,a:hover 必须被置于 a:link 和 a:visited 之后,才是有效的。
在 CSS 定义中,a:active 必须被置于 a:hover 之后,才是有效的。

?为哈

程序是从上到下执行的(了解程序必备基础概念)

通用伪类

1
2
3
4
/*第一个selector*/
selector:first-child{

}

示例

1
2
3
4
5
6
.test p{
color: #666;
}
.test p:first-child{
color: #ff0000;
}
1
2
3
4
5
<div class="test">
<p>first-child伪类的测试</p>
<p>first-child伪类的测试</p>
<p>first-child伪类的测试</p>
</div>

这样是有效的,可以看到第一行样式变成了红色
但是,当我把html改成这样

1
2
3
4
5
6
<div class="test">
<div>占据第一行</div>
<p>first-child伪类的测试</p>
<p>first-child伪类的测试</p>
<p>first-child伪类的测试</p>
</div>

可以看到,第一个p标签并没有有变成红色
所以,关于伪类我们要这样理解:

目标元素是第一个子节点样式(它是p标签且是第一个孩子)

你觉得你理解了这句话的含义了,好,接下来,我再把html代码改成这样

1
2
3
4
5
6
7
8
<div class="test">
<p>占据第一行</p>
<p>first-child伪类的测试</p>
<div>
<p>first-child伪类的测试</p>
</div>
<p>first-child伪类的测试</p>
</div>

这样我们得到的是两段文字变成了红色
仔细回味之前的那句话,嗯,刷新了认识,重点在于第一个子节点
这就结束了?
不!不!不!我还可以把样式做一个小小的处理

1
2
3
4
5
6
.test p{
color: #666;
}
.test>p:first-child{
color: #ff0000;
}

配上之前一样的html代码

1
2
3
4
5
6
7
8
<div class="test">
<p>占据第一行</p>
<p>first-child伪类的测试</p>
<div>
<p>first-child伪类的测试</p>
</div>
<p>first-child伪类的测试</p>
</div>

现在又变成只有一行变红了

伪元素语法

selector:pseudo-element {property:value;}

常见伪元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*匹配文本的首行添加样式*/
p:first-line{
color: #ff0000;
text-decoration: underline;
}
/*匹配文本的首字母添加样式*/
p:first-letter{
color: #ff0000;
font-weight: bold;
}
/*在元素的内容前面插入新内容*/
p:before{
content: '我在前面';
}
p:before{
content: url(icon.png);
}
p:before{
content: '';
display: inline-block;
width: 10px;
height: 10px;
border: 1px solid #ff0000;
}
/*在元素的内容后面追加新内容*/
p:after{
content: '我在前面';
}

:before:after这两个伪元素的content属性有着强大的功能,见证奇迹

1
2
3
<div class="test" data-text="才怪">
<p>我是老大</p>
</div>

1
2
3
test:after{
content: attr(data-text);
}

我们读取到了元素的data-text属性,很强大!!!

何莹亮原创技术文章,转载请注明出处:https://heyingliang.github.io/mark/2018/07/20/pseudoClass/

目录