How to Style Your Code Snippets

When you write a blog post and need to add code snippets, they should stand out. You have two choices: use a Syntax Highlighter or style the code yourself.

Syntax Highlighter

A Syntax Highlighter is a tool styles the code snippet for you. You can use one of the following tools to style the syntax.

  • Prettify, a Javascript solution the highlights source code syntax.
  • Snippet, a jQuery Syntax Highlighter.
  • SyntaxHighlighter another Javascript Syntax Highlighter tool.
  • Prism, lightweight syntax highlighter that works with HTML5.

Style Your Code Snippets Yourself

If you want to handle the styling yourself, you’ll need to use HTML and CSS. You need to useĀ  HTML tags like <pre> and <code>. For extra styling, you can place your code inside a div tag.

Write the HTML

  1. Wrap the code snippet in a div tag like <div id=”codeSnippet”>
  2. Add your code snippet between the <pre> and <code> tags. The pre tag displays the text exactly as type preserving spaces and tabs.

<div id="codeSnippet">
<pre><code><script type="text/javascript">
$(document).ready(function() {
fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...

Write the CSS

In your CSS, add styles for pre, code, div and anything else that you need. In the following example, I created a style that mimics an old DOS computer screen. I used pre, code, a div and a class to achieve that look. Here is the simple CSS:

/* Code Styles */
pre {
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;}

code {
font-family: Courier, 'New Courier', monospace;
font-size: 12px;}

#codeStyler {
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
margin: 1em 0;}

.computerGreen {
background-color: #000000;
color: green;}

When you view at your results in a browser, you get a code snippet that looks like this:CSS Code SnippetLine numbers can help to make the snippet more readable. If you want to add additional style to your numbers, try Styling ordered list numbers.