Syntax Highlighting in WordPress

When I started to setup this blog, I knew I would need to post a lot of code in order to describe what I wanted to. After some googling around I found WP-Syntax which among the various syntax highlighters appears to be the most supported (it and various other add-ons seem to be available in the WP Plugins for automatic install). I recommend WP-Syntax itself plus the plugin called WP-Syntax Button, which provides a simple button to click in the visual post editor. Here’s an example of some Javascript highlighting:

// Trying out some prototypal inheritance
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();

However it isn’t all roses…at least for me, using the Twenty-Eleven theme from WordPress, I ran into trouble. The code was too large and bulky looking on the screen, the styling was all wrong. Apparently the styling of the theme was overriding the styling for the syntax highlighter, as the theme uses #content context which the page sees as more specific than the styles defined for WP-Syntax.

In order to resolve should you see similar issues, you can go into plugins, edit the wp-syntax.css file for WP-Syntax, and prefix each element with #content. Like this:

#content .wp_syntax {
  color: #100;
  background-color: #f9f9f9;
  border: 1px solid silver;
  margin: 0 0 1.5em 0;
  overflow: auto;
/* IE FIX */
#content .wp_syntax {
  overflow-x: auto;
  overflow-y: hidden;
  padding-bottom: expression(this.scrollWidth > this.offsetWidth ? 15 : 0);
  width: 100%;
#content .wp_syntax table {
  border-collapse: collapse;
#content .wp_syntax div, .wp_syntax td {
  vertical-align: top;
  padding: 2px 4px;
#content .wp_syntax .line_numbers {
  text-align: right;
  background-color: #def;
  color: gray;
  overflow: visible;
/* potential overrides for other styles */
#content .wp_syntax pre {
  margin: 0;
  width: auto;
  float: none;
  clear: none;
  overflow: visible;
  font-size: 12px;
  line-height: 1.333;
  white-space: pre;

Note the #content tags at the beginning. This still left me with some issues with line numbering, which I haven’t yet gotten around to figuring out.

Update: After posting this, I found this blog which has a much better description of the process and correctly utilises a child theme:

This entry was posted in Wordpress and tagged , , , , , . Bookmark the permalink.

One Response to Syntax Highlighting in WordPress

  1. Matthias says:

    Gooԁ waу of ԁeѕcribing, anԁ pleasаnt post to get faсts cοncеrnіng mу preѕentation subject matter, whiсh i
    am going tο convеy in ѕchool.

Leave a Reply to Matthias Cancel reply

Your email address will not be published. Required fields are marked *