这里主要介绍利用before选择器和after选择器在页面中插入内容的方法。
1、插入文字
<style>
h2:before{
content:"这里是文字";
//可以在这里为加入的文字设置大小、颜色等属性}
</style>
如果要对页面中个别的h2 标签前面不添加内容,只需给不需要添加内容的标签设置样式,然后设置content:none; 代码如下:
<style>
h2.sample:before{
content:none;
}
</style>
2、插入图像文件
<style>
h2:before{
content:url(mark.png);}
</style>
可以通过添加背景图像的方式在元素前面添加图像;
<style>
h2{
background-image:url(mark.png);
background-repeat:no-repeat;
padding-left:28px; //这里根据图像大小设置合适的位置
}
</style>
3、使用content属性插入项目编号
这里的h1 可以是任意元素标签 mycounter是计数器,而且content中可以追加文字
h1:before{
content:"第"counter(mycounter)"章";
}
h1
{counter-increment:mycounter;
}
counter中还可以指定编号的种类:upper-alpha 指定大写字母,upper-roman指定大写罗马字母,编号的种类可以使用list-style-type中的值。
用法如下:
content:counter(mycounter,upper-alpha);
编号嵌套
h1:before{
content:counter(mycounter)".";
}
h1
{counter-increment:mycounter;
counter-reset:subcounter; //编号重置
}
h2:before{
content:counter(subcounter)".";
}
h2
{counter-increment:subcounter;
}