How to include code in your web page

Including code in your html is actually quite simple. Wrap the code in a <code> tag and you are done: printf("hello\n"); Or for a code block you can wrap the <code> in a <pre> to preserve formatting. This would look like this:
10 print "hello world!" 
20 goto 10 
This already looks quite decent with some simple css rules, but it would be even nicer with syntax highlighting, wouldn't it? This is where Google Code Prettify steps in, a javascript library that searches for <code> tags in your page and beautifies the code inside by adding some extra markup. To use it include this .js in your page:

<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=sons-of-obsidian"></script>

Now add the class prettyprint to any code block you would like to be beautified: <code class="prettyprint"> The prettifier will try to guess the language used and apply syntax highlighting accordingly. The same BASIC code fragment will now look like this:
10 print "hello world!" 
20 goto 10 

more options

There are a couple of options to influence the looks of your code. For one the prettifier only adds spans and classes to your code, the actual looks depend on the skin. On this page the Sons of Obsidian skin is used, you can pick a different skin from the gallery by changing the url parameter 'skin' of the .js-include.

Some other options are available by adding classes to you code section. Line numbers can be turned on by adding the linenums class: class="prettyprint linenums"
public class Hello { 
    private String name; 
     
    public Hello(String name) { 
        this.name = name; 
    } 
 
    public void sayIt() { 
        System.out.println("Hello " + name); 
    } 
} 
For the full story have a look at the getting started page on GitHub.

Update October 2022: the code-prettify GitHub project has since been archived, meaning it won't receive updates and could eventually disappear altogether. Additionally, Google doesn't host the javascript file anymore, and the cdn site rawgit.com which is now recommended in the project's README is EOL, so if you want to use this on your website, I'd recommend to host your own copy, or find another cdn that hosts it. You could also try out an alternative project that is still under active development, for example highlight.js (haven't tried this library myself).


related blogs: