Syntax highlighting is one of the basic things that technology, programming and web design site owners want on their sites and blogs. Google Code Prettify is one of the popular (I must say the best) ways to setup code highlighting on your site.

Why should I use Google Code Prettify?

It’s fast, efficiently programmed and supports multiple code themes for syntax highlighting – this way it beats other free projects on the same topic.

In this article we’ll see how to get it installed on our site without messing much with the code.

Setting up Google Code Prettify on a website

First off, we have to add the JavaScript that initializes Google Code Prettify on our site. In order to do that, edit the HTML of your site, and look for </body> (closing body tag) and copy-paste the following JavaScript just below it:

<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?lang=css&skin=sunburst"></script>

Save the changes.

Note: The Code Prettify tries to detect your code type automatically, however, if you’re not getting it work for your code, specify the lang attribute as given in the list of supported languages. You can also choose a different skin from the available ones.

Now, whenever you have to show code syntax on your site or blog posts, just wrap it in parsed form between <pre class="prettyprint"></pre> or <code class="prettyprint"></code> tags. Did you notice that these tags carry a class="prettyprint" attribute, that makes the Google code prettify script to target it and style it dynamically.

For a demonstration, I’m displaying some sample prettified code here with the help of Google Code Prettify. I have used the Sunburst theme for that:

<script type="text/javascript">
// Say hello world until the user starts questioning
// the meaningfulness of their existence.
function helloWorld(world) {
   for (var i = 42; --i >= 0;) {
      alert('Hello ' + String(world));
   }
}
</script>
<style>
p { color: pink }
b { color: blue }
u { color: "umber" }
</style>

Additionally, if you’re a CSS ninja, you can also create a separate style for your syntax highlighting purposes. Hope you find it useful.