- CSS3网页设计从入门到精通(微课精编版)
- 前端科技
- 667字
- 2025-02-20 07:05:46
4.4 内容生成和替换
content属性属于内容生成和替换模块,可以为匹配的元素动态生成内容。这样就能够满足在CSS样式设计中临时添加非结构性的样式服务标签或者补充说明性内容等。
权威参考:http://www.w3.org/TR/css3-content/。
4.4.1 定义content
content属性的简明语法如下:
content: normal | string | attr() | url() | counter() | none;
取值简单说明如下。
normal:默认值,表现与none值相同。
string:插入文本内容。
attr():插入元素的属性值。
url():插入一个外部资源,如图像、音频、视频或浏览器支持的其他任何资源。
counter():计数器,用于插入排序标识。
none:无任何内容。
提示:content属性早在CSS2.1中就被引入,可以使用:before和:after伪元素生成内容。此特性目前已被大部分的浏览器支持,另外Opera 9.5+和Safari 4已经支持所有元素的content属性,而不仅仅是:before和:after伪元素。在CSS3 Generated Content工作草案中,content属性添加了更多的特征,如插入以及移除文档内容的能力,可以创建脚注、段落注释等。但目前还没有浏览器支持content的扩展功能。
【示例1】下面示例使用content属性为页面对象添加外部图像,演示效果如图4.30所示。


图4.30 动态生成图像演示效果
注意:content属性通常与:after及:before伪元素一起使用,在对象前或后显示内容。
【示例2】下面示例使用content属性把超链接的URL字符串动态显示在页面中,演示效果如图4.31所示。


图4.31 把属性值显示在页面中
4.4.2 案例:应用content
下面结合多个示例练习content在网页中的应用。
【示例1】下面示例使用content属性,配合CSS计数器设计多层嵌套有序列表序号样式,效果如图4.32所示。


图4.32 使用CSS技巧设计多级层级目录序号
【示例2】下面示例使用content为引文动态添加引号,演示效果如图4.33所示。


图4.33 动态生成引号
【示例3】下面示例使用content为超链接动态添加类型图标,演示效果如图4.34所示。


图4.34 动态生成超链接类型图标