Styling HTML Code Blocks Using Only CSS & CSS Counters


/ Published in: CSS
Save to your folder(s)

Learn how to style the HTML code element with CSS using CSS counters. CSS counters are the CSS equivalent to variables. In my tutorial I use CSS counters to emulate line numbers for my code block.


Copy this code and paste it in your HTML
  1. <script type="text/javascript">
  2. //http://www.somacon.com/p355.php
  3. String.prototype.trim = function()
  4. {
  5. return this.replace(/^\s+|\s+$/g,"");
  6. }
  7. //http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_21478202.html
  8. function codeToList()
  9. {
  10. //Convert code elements to ordered lists
  11. var code = document.getElementsByTagName("code")
  12. for (i = 0; i < code.length; i++)
  13. {
  14. code[i].innerHTML = "<ol class='code'>" + code[i].innerHTML.replace(/\n/g, "<li>").trim() + "</ol>";
  15. } //end for
  16. //Apply zebra stripes
  17. if (document.getElementsByClassName)
  18. {
  19. var code = document.getElementsByClassName("code");
  20. for (i = 0; i < code.length; i++)
  21. {
  22. var li = code[i].getElementsByTagName("li")
  23. var cn = "odd";
  24. for (x = 0; x < li.length; x++)
  25. {
  26. li[x].className = cn;
  27. cn == "odd" ? cn = "even" : cn = "odd"; //condition ? true : false
  28. } //end for
  29. } //end for
  30. } //end if
  31. } //end function
  32. window.onload = DOMReadyAll;
  33. function DOMReadyAll()
  34. {
  35. codeToList();
  36. }
  37. </script>
  38. <style type="text/css">
  39. body { font-size: 12px; width: 600px; }
  40. .code
  41. {
  42. background: url(/files/images/template/code_bg2.png) repeat left top;
  43. border: 1px solid #cccccc;
  44. list-style-type: none;
  45. margin: 0px;
  46. padding: 0px;
  47. overflow: auto;
  48. width: 550px;
  49. }
  50. .code li
  51. {
  52. color: #669933;
  53. font-family: "Consolas", "Courier New", Courier, mono;
  54. line-height: 0px; /* to remove white border issue */
  55. white-space: pre;
  56. }
  57. .code { counter-reset: li; }
  58. .code li:before
  59. {
  60. counter-increment: li;
  61. content: counter(li) ". ";
  62. background: #ececec;
  63. border-right: 1px solid #cccccc;
  64. color: #555555;
  65. display: inline-block;
  66. font-family: Arial, Helvetica, sans-serif;
  67. line-height: 30px; /* minumum line height = 24, smaller causes white border issue */
  68. margin-right: 20px;
  69. padding-right: 5px;
  70. text-align: right;
  71. width: 50px;
  72. }
  73. /*
  74. .code li:nth-child(odd) { background: #ffffff; }
  75. .code li:nth-child(even) { background: #fafafa; }
  76. .code .odd { background: #ffffff; }
  77. .code .even { background: #fafafa; }
  78. */
  79. .code li:empty { display: none; }
  80. </style>

URL: http://www.nealgrosskopf.com/tech/thread.asp?pid=33

Report this snippet Tweet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.

AltStyle によって変換されたページ (->オリジナル) /