CSS :before 伪元素

实例

此样式会在每个 h1 元素之前播放一段声音:

  1. h1:before
  2. {
  3. content:url(beep.wav);
  4. }

浏览器支持

所有主流浏览器都支持 :before 伪元素。

定义和用法

:before 伪元素在元素之前添加内容。

这个伪元素允许创作人员在元素内容的最前面插入生成内容。默认地,这个伪元素是行内元素,不过可以使用属性 display 改变这一点。

实例

使用 :before 在元素内容之前插入内容

本例演示如何使用 :before 在元素内容之前插入图像。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style type="text/css">
  5. h1:before {content:url(/i/logo_white.gif)}
  6. </style>
  7. </head>
  8. <body>
  9. <h1>This is a heading</h1>
  10. <p>The :before pseudo-element inserts content before an element.</p>
  11. <h1>This is a heading</h1>
  12. <p><b>注释:</b>如果已规定 !DOCTYPE,那么 Internet Explorer 8 (以及更高版本)支持 content 属性。
  13. </body>
  14. </html>

相关页面

CSS 教程:CSS 伪元素

CSS 参考手册:CSS :after 伪元素