This site will look much better in a browser that supports web standards, but it is accessible to any browser or Internet device.

John McSweeney - picture detail

John McSweeney

May 9, 2008, 10:07 pm

Website Design

Displaying Code

 

When displaying code on a web page, one needs to pay close attention to formatting. Before presenting some solutions, compare these two identical snippets of Java code.

This first extract was copied from a code editor and pasted directly into a Dreamweaver document. Any formatting that was present in the code editor has been lost.

// establish a server socket
try{
Vector connections = new Vector(10,2);
ServerSocket ss = new ServerSocket(3000);
// loop waiting for a client to connect
while(true) {
System.out.println("Waiting for client " + (clientCount+1)
+ " to connect" );
Socket s = ss.accept();
// connection with client made
clientCount++; // rest of code omitted
} //end while
} //end try

 

The second version makes use of HTML preformatting tags <pre></pre>.

    // establish a server socket
    try{
       Vector connections = new Vector(10,2);
       ServerSocket ss = new ServerSocket(3000);
       // loop waiting for a client to connect
       while(true) {
          System.out.println("Waiting for client " + (clientCount+1)
                              + " to connect" );
          Socket s = ss.accept();
          // connection with client made
          clientCount++;
          // rest of code omitted
       } //end while
    } //end try
   

To use this method:

  1. Open an HTML, or text editor, and write the <pre></pre> tags directly into the HTML.
  2. Place the cursor between the two tags and paste in the code, which can be copied from a code editor.

Note that without preformatting tags, a browser will compress any white space to a single space character. Consequently, without them, any tabs or returns that you type between paragraph tags will be lost.

By default a browser will display preformatted text as a fixed width font, probably Courier, which will satisfy most authors.

I have also defined a CSS rule to be matched to any preformatting tags.

pre {
  color: Navy;
} 

However, I like more control over appearance than that offered by preformatting tags. Fortunately CSS provides a solution.

Next page » Displaying Code with a CSS Class Selector

Previous page « Mathcad and MathML