伪元素::before和::after

来源:互联网 发布:美工设计经理岗位职责 编辑:程序博客网 时间:2024/04/30 00:40

2.10.3 伪元素::before和::after

对于“::before”和“::after”来说,大家并不多见,但“:before”和“:after”,或许不会陌生,因为清除浮动就使用这两个伪类。

“::before”和“::after”不是指存在于标记中的内容,而是可以插入额外内容的位置。尽管生成的内容不会成为DOM的一部分,但它同样可以设置样式。

要为伪元素生成内容,还需要配合content属性。例如,假设在页面上所有外部链接之后的括号中附加它们所指向的URL,无须将URL硬编码到标记中,可以结合使用一个属性选择器和“::after”伪元素。
 

  1. a[herf^=http]::after {  
  2.   content:"(" attr(herf) ")";  

如今在CSS3中使用“::before”和“::after”越来越多见,例如给链接添加ICON的效果。Font Awesome站点制作的ICON就使用伪元素“::before”和“::after”,下面截取部分代码。
 

  1. /*  Font Awesome styles  
  2.     ------------------------------------------------------- */  
  3. [class^="icon-"]:before,  
  4. [class*=" icon-"]:before {  
  5.   font-family: FontAwesome;  
  6.   font-weight: normal;  
  7.   font-style: normal;  
  8.   display: inline-block;  
  9.   text-decoration: inherit;  
  10. }  
  11. a [class^="icon-"],  
  12. a [class*=" icon-"] {  
  13.   display: inline-block;  
  14.   text-decoration: inherit;  
  15. }  
  16. /* makes the font 33% larger relative to the icon container */  
  17. .icon-large:before {  
  18.   vertical-align: middle;  
  19.   font-size: 1.3333333333333333em;  
  20. }  
  21. .btn [class^="icon-"],  
  22. .nav-tabs [class^="icon-"],  
  23. .btn [class*=" icon-"],  
  24. .nav-tabs [class*=" icon-"] {  
  25.   /* keeps button heights with and without icons the same */  
  26.  
  27.   line-height: .9em;  
  28. }  
  29. li [class^="icon-"],  
  30. li [class*=" icon-"] {  
  31.   display: inline-block;  
  32.   width: 1.25em;  
  33.   text-align: center;  
  34. }  
  35. li .icon-large:before,  
  36. li .icon-large:before {  
  37.   /* 1.5 increased font size for icon-large * 1.25 width */  
  38.  
  39.   width: 1.875em;  
  40. }  
  41. ul.icons {  
  42.   list-style-type: none;  
  43.   margin-left: 2em;  
  44.   text-indent: -0.8em;  
  45. }  
  46. ul.icons li [class^="icon-"],  
  47. ul.icons li [class*=" icon-"] {  
  48.   width: .8em;  
  49. }  
  50. ul.icons li .icon-large:before,  
  51. ul.icons li .icon-large:before {  
  52.   /* 1.5 increased font size for icon-large * 1.25 width */  
  53.   vertical-align: initial;  
  54. }  
  55. .icon-bullhorn::before {  
  56.   content: "\f0a1";  
  57. }  
  58. .icon-beaker::before {  
  59. content: "\f0c3";  

效果如图2-50所示。


0 0