:before和:after是CSS中定义的伪元素,配合content属性,可以在元素的前面或后面插入新元素,content即插入元素的值,
这些添加不会出现在DOM中,不会改变文档内容,不可复制,仅仅是在css渲染层加入。
所以不要用:before或:after展示有实际意义的内容,尽量使用它们显示修饰性内容,例如图标。
简单的实例如下:在每个 <p> 元素的内容之前插入新内容:
p:before
{
content:"台词:";
}
可以有如下的定义值
值 | 说明 |
---|---|
none | 设置Content,如果指定成Nothing |
normal | 设置content,如果指定的话,正常,默认是"none"(该是nothing) |
counter | 设定计数器内容 |
attr(attribute) | 设置Content作为选择器的属性之一。 |
string | 设置Content到你指定的文本 |
open-quote | 设置Content是开口引号 |
close-quote | 设置Content是闭合引号 |
no-open-quote | 如果指定,移除内容的开始引号 |
no-close-quote | 如果指定,移除内容的闭合引号 |
url(url) | 设置某种媒体(图像,声音,视频等内容) |
inherit | 指定的content属性的值,应该从父元素继承 |
其中计数器counter使用实例如下
body {
counter-reset: section; /* Set a counter named 'section', and it`s initial value is 0. */
}
h3::before {
counter-increment: section; /* Increment the value of section counter by 1 */
content: counter(section); /* Display the value of section counter */
}
<h3>Introduction</h3>
<h3>Body</h3>
<h3>Conclusion</h3>
Result
而counters是另一种CSS方法,适用于嵌套的计时器,使用方法如下:
Nesting counters
A CSS counter can be especially useful for making outlined lists, because a new instance of the counter is automatically created in child elements. Using the counters()
function, separating text can be inserted between different levels of nested counters.
Example of a nested counter
CSS
ol {
counter-reset: section; /* Creates a new instance of the
section counter with each ol
element */
list-style-type: none;
}
li::before {
counter-increment: section; /* Increments only this instance
of the section counter */
content: counters(section, ".") " "; /* Combines the values of all instances
of the section counter, separated
by a period */
}
HTML
<ol>
<li>item</li> <!-- 1 -->
<li>item <!-- 2 -->
<ol>
<li>item</li> <!-- 2.1 -->
<li>item</li> <!-- 2.2 -->
<li>item <!-- 2.3 -->
<ol>
<li>item</li> <!-- 2.3.1 -->
<li>item</li> <!-- 2.3.2 -->
</ol>
<ol>
<li>item</li> <!-- 2.3.1 -->
<li>item</li> <!-- 2.3.2 -->
<li>item</li> <!-- 2.3.3 -->
</ol>
</li>
<li>item</li> <!-- 2.4 -->
</ol>
</li>
<li>item</li> <!-- 3 -->
<li>item</li> <!-- 4 -->
</ol>
<ol>
<li>item</li> <!-- 1 -->
<li>item</li> <!-- 2 -->
</ol>
Result
参考资料:https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Lists_and_Counters/Using_CSS_counters
http://www.runoob.com/cssref/pr-gen-content.html