Adding code snippet formatting to web pages

April 23 2010
asp.net    css

While building this blog I ran into the problem of getting code (as in source code) to display in a format that was easy to read. HTML provides the pre and code elements which give semantics to the source code posted in a blog. However, it doesn't look code displayed in your favourite IDE. My first attempt was a styling of the code element in css, something like:

code
{
border: solid 1px #000;
background-color: #808080;
font-family: Courier; font-size: 10px;
}

This helped a little, but when I pasted multiple line code, such as a C# class, the code was still hard to read. Any code snippets included need to be easily readable, and this includes syntax highlighting an numbers and I'd seen this on any number of blogs I've visited over the years, so I knew it existed.

I followed the trail and after an hour or two came to SyntaxHighlighter which by looks is what the majority of those blogs I've visited use. It's peasy to set up. I won't go through the entire process because it'll just be rehashing the linked page. If you want a quick reference, here's the steps I took to set it up.

1. Add code to the page (master page in my asp.net case).

 
<link rel="stylesheet" type="text/css" href="/css/SyntaxHighlighter/shCore.css" />
<link rel="stylesheet" type="text/css" href="/css/SyntaxHighlighter/shThemeDefault.css" />
<script type="text/javascript" src="/Scripts/SyntaxHighlighter/shCore.js"></script>


<!-For each of the languages I want different highlighting for -->
<script type="text/javascript" src="/Scripts/SyntaxHighlighter/shBrushCSharp.js"></script>
<script type="text/javascript" src="/Scripts/SyntaxHighlighter/shBrushSql.js"></script>
<script type="text/javascript" src="/Scripts/SyntaxHighlighter/shBrushVb.js"></script>
<script type="text/javascript" src="/Scripts/SyntaxHighlighter/shBrushXml.js"></script>

2. Start the SyntaxHighlighter engine with your desired properites by adding the following to the bottom of your page, just above the body tag.

     
<script type="text/javascript" />
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = '/Scripts/SyntaxHighlighter/clipboard.swf';
SyntaxHighlighter.defaults['wrap-lines'] = false;
SyntaxHighlighter.all();
</script>

3. Surround any code in pre tags with the brush class. The SyntaxHighlighter engine uses this to format the code in the language specified. See the SyntaxHighlighter website for details.

 
<pre class="brush: html">My Html Code<pre>

Post a comment

comments powered by Disqus