Return to Snippet

Revision: 11579
at February 10, 2009 08:04 by neal_grosskopf


Initial Code
<script type="text/javascript">
//http://www.somacon.com/p355.php
String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g,"");
}

//http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_21478202.html
function codeToList()
{
	//Convert code elements to ordered lists
	var code = document.getElementsByTagName("code")
	for (i = 0; i < code.length; i++)
	{
		code[i].innerHTML = "<ol class='code'>" + code[i].innerHTML.replace(/\n/g, "<li>").trim() + "</ol>";
	} //end for
	
	//Apply zebra stripes
	if (document.getElementsByClassName)
	{
		var code = document.getElementsByClassName("code");
		for (i = 0; i < code.length; i++)
		{	
			var li = code[i].getElementsByTagName("li")
			var cn = "odd";						
			for (x = 0; x < li.length; x++)
			{
				li[x].className = cn;				
				cn == "odd" ? cn = "even" : cn = "odd"; //condition ? true : false
			} //end for
		} //end for
	} //end if
		
} //end function

window.onload = DOMReadyAll;
function DOMReadyAll()
{
	codeToList();
}
</script>

<style type="text/css">
body { font-size: 12px; width: 600px; }

.code
{
background: url(/files/images/template/code_bg2.png) repeat left top;
border: 1px solid #cccccc;
list-style-type: none;
margin: 0px;
padding: 0px;
overflow: auto;
width: 550px;
}

.code li
{
color: #669933;
font-family: "Consolas", "Courier New", Courier, mono;
line-height: 0px; /* to remove white border issue */
white-space: pre;
}

.code { counter-reset: li; }
.code li:before
{
counter-increment: li;
content: counter(li) ". ";
background: #ececec;
border-right: 1px solid #cccccc;
color: #555555;
display: inline-block;
font-family: Arial, Helvetica, sans-serif;
line-height: 30px; /* minumum line height = 24, smaller causes white border issue */
margin-right: 20px;
padding-right: 5px;
text-align: right;
width: 50px;
}

/*
.code li:nth-child(odd) { background: #ffffff; }
.code li:nth-child(even) { background: #fafafa; }
.code .odd { background: #ffffff; }
.code .even { background: #fafafa; }
*/
.code li:empty { display: none; }
</style>

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

Initial Description
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.

Initial Title
Styling HTML Code Blocks Using Only CSS & CSS Counters

Initial Tags
css, html

Initial Language
CSS