Setup Google Code Prettify on your Website

A beginner’s guide to install and use Google Code Prettify aka Prettyprint on your website with least coding skills required.

Setup Google Code Prettify on your Website

Syntax highlighting is one of the basic needs of the websites that feature programming code. Google Code Prettify aka Prettyprint is one of the popular (for me, the best) ways to setup code highlighting on your site.

Why I use Google Code Prettify

In all of my existing websites, I use Google prettify to highlight and decorate the code bits. I use it because it’s fast, efficiently programmed and supports multiple code themes for syntax highlighting.

Sons of Obsidian color theme
Code decorated with Sons of Obsidian color theme

All of the decorated code you see here is done by GCP only. 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

  1. First off, download the latest version of GCP from here.
  2. Extract the files from the downloaded archive.
  3. Look for the prettify.js and prettify.css in the extracted files. Upload these two files on your web server.
  4. The JavaScript file will help assigning styles to the code bits, and the CSS file will carry those styles.
  5. Lets add the CSS file in our website. Add the below given code just above the </head> (closing head tag) in your site’s HTML:
    <link rel="stylesheet" href="http://yoursite.tld/prettify.css" />

    Change the URL path above to your hosted prettify CSS file’s path.

  6. Now, we are going to call prettify.js and then initialize the Google Code prettify on our site. Place the following block of code just before the </body> (closing body tag) in your website’s HTML:
    <script src="http://yoursite.tld/prettify.js"></script>
    window.onload = (function(){ prettyPrint(); });

    Again, be sure to replace the URL in the above code to your hosted prettify JS file’s URL.

  7. Finally, save all the changes.

That’s it. We’re done with the installation. From now whenever you add a block of code, add .prettyprint to the <pre> tag wrapping your code in parsed form — it will be highlighted automatically. Below example demonstrates it well:

<pre class"prettyprint">
/* This is some CSS code */
.red { color: red; }
.green { color: green; }
.blue {color: blue; }

The Code prettify is smart enough to detect the code type and then style it accordingly. You may check here the list of it’s supported language, and also the style library it provides for code highlighting.

What prettify color themes I use here

Currently, I’m using a modded GitHub-style theme created by jmblog, check more themes like it here. You may also create a color theme by yourself, but that I’ll cover some other day.

Thanks for the read :)