本文主要讲解css伪元素的讲解及伪元素用法
css伪元素
- :first-letter
- :first-line
- :before
- :after
:first-letter伪元素
他的作用是改变文本的第一个字母添加特殊样式;
<style>
P{
color: aqua;
font-size: 14px;
}
p:first-letter{
color: red;
font-weight: 800;
font-size: 20px;
}
</style>
<P>这是一段文字,测试:first-letter</P>
这样一段代码,最终的执行结果是如下图:
:first-line伪元素
主要作用是改变文本段落首行的样式。
<style>
P{
color: aqua;
font-size: 14px;
line-height: 20px;
}
p:first-letter{
color: red;
font-weight: 800;
font-size: 30px;
}
P::first-line{
color: blue;
font-size: 20px;
line-height: 30px;
}
</style>
<p>
同样是一段文字测试,这次用br标签对他进行换行,多行文字对比,
<br/>
这是第二行的文字内容
<br/>
这是第三行的文字内容
<br/>
这是第四行的文字内容
</p>
这样一段代码,最终的执行结果是如下图:
需要注意的是,:first-line和 :first-letter 只能用于块级元素,他们是可以同时使用的
:before伪元素
可以在元素的内容前面插入新内容,可抽象的理解为在标签内部前面创建了一个新的标签;
<style>
div, p{
color: aqua;
font-size: 16px;
}
p:before{
content: url(img1.png);
width: 50px;
height: 50px;
}
div::before{
content:'before';
color: red;
}
h3:before{
content:'';
width: 100px;
height: 40px;
background-color: blueviolet;
display: inline-block;
}
</style>
<p>
这是一个p标签,测试:before伪元素
</p>
<div>
这是一个div标签,测试:before伪元素
</div>
<h3>这是一个h3标签,测试:before伪元素</h3>
这样一段代码,最终的执行结果是如下图:
content这个属性很重要,是添加标签内容的载体吧。
:after伪元素
:after伪元素可以在元素的内容之后插入新内容,用法和:before一样的,
<style>
div, p, h3{
color: aqua;
font-size: 16px;
}
p:before{
content: url(img1.png);
width: 50px;
height: 50px;
}
p:after{
content: url(img1.png);
width: 50px;
height: 50px;
}
div::before{
content:'before';
color: red;
}
div:after{
content:'after';
color: rgb(15, 248, 46);
}
h3:before{
content:'';
width: 100px;
height: 40px;
background-color: blueviolet;
display: inline-block;
}
h3:after{
content:'';
width: 100px;
height: 40px;
background-color:red;
display: inline-block;
}
</style>
<p>
这是一个p标签,测试:before伪元素
</p>
<div>
这是一个div标签,测试:before伪元素
</div>
<h3>这是一个h3标签,测试:before伪元素</h3>
这样一段代码,最终的执行结果是如下图:
本文主要参考W3C的内容来写的。如有错误,欢迎指出!
下一篇文章写些利用:before和:after来制作写五角星,多边形等一些特殊的样式结构。