三、CSS3伪元素

三、CSS3伪元素

3.1 ::before

元素::before

表示在原有内容之前插入

必须书写的一个属性content(内容) 属性值可以书写要添加的内容或者””

行内元素不能设置宽高,想设置宽高要转块

1
2
3
4
5
6
7
8
9
p::before {
/* 必须书写content 不能省略 */
content: "我是前面增加的内容";
font-size: 50px;
color: red;
font-weight: bold;
}

<p>我是段落</p>

NUgkM4.png

3.2 ::after

元素::after

表示在原有内容之后插入

必须书写的一个属性content(内容) 属性值可以书写要添加的内容或者””

行内元素不能设置宽高,想设置宽高要转块

1
2
3
4
5
6
7
8
/* 伪元素:在CSS书写结构 */
p::after {
/* 必须书写content 不能省略 */
content: "我是后面增加的内容";
font-size: 50px;
color: red;
font-weight: bold;
}

NUgZZR.png

3.3 应用

3.3.1 先导符号的使用

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<div class="box">
<ul>
<li><a href="">文字文字文字文字文字文字文字文字文字文字</a></li>
<li><a href="">文字文字文字文字文字文字文字文字</a></li>
<li><a href="">文字文字文字文字文字文字</a></li>
<li><a href="">文字文字文字文字文字文字文字文字文字</a></li>
<li><a href="">文字文字文字文字文字文字文字文字文字文字</a></li>
<li><a href="">文字文字文字文字</a></li>
</ul>
</div>

ul {
list-style: none;
}
.box {
width: 700px;
border: 1px solid #000;
margin: 50px auto;
padding: 20px;
}
.box ul li {
height: 60px;
line-height: 60px;
}
.box ul li a {
display: block;
height: 60px;
/* a 是before父节点 */
position: relative;
padding-left: 20px;
}
.box ul li a::before {
/* 必须书写content */
content: "";
/* 行内元素 绝对定位 脱标 可以设置宽高*/
position: absolute;
left: 0px;
top: 23px;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #333;
}
.box ul li a:hover {
color:orange;
}
.box ul li a:hover::before {
/* 伪元素鼠标悬停效果 */
background-color: red;
}

NUgaJf.png

3.3.2 清除浮动的影响

内墙法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<div class="box">
<p></p>
<p></p>
<p></p>
<p></p>
<div class="cl"></div>
</div>
<div class="box">
<p></p>
<p></p>
<p></p>
<p></p>
<div class="cl"></div>
</div>

.cl {
clear: both;
}

利用内墙法的原理添加伪元素清除浮动:

1
2
3
4
5
6
7
/* 使用伪元素清除浮动 */
.box::after {
content: "";
/* 行内元素 转块 换行形成一堵墙 */
display: block;
clear: both;
}

NUg7wR.png

3.3.3 模拟交互效果

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
29
30
31
32
33
34
<div class="box">
<p>文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字</p>
</div>

.box {
width: 300px;
height: 300px;
border: 1px solid #000;
margin: 50px auto;
line-height: 40px;
position: relative;
/* 溢出隐藏 */
overflow: hidden;
}
/* 蒙版 */
.box::after {
content: "查看更多";
position: absolute;
width: 300px;
height: 300px;
background-color: rgba(0,0,0,.7);
/* 文字的水平居中 */
text-align: center;
/* 文字的垂直居中 */
line-height: 300px;
left: 0;
top: 300px;
color: #fff;
font-weight: bold;
}
/* 鼠标进入出现蒙版 */
.box:hover::after {
top: 0;
}

NUgx6e.png

点击查看

本文标题:三、CSS3伪元素

文章作者:Mango

发布时间:2020年06月30日 - 21:26:47

最后更新:2020年06月30日 - 21:44:19

原始链接:https://mango185.github.io/post/d9448500.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------