Take a quick look at a handful of teen tutorial websites and you will notice a recurring trend: code is distributed through a multitude of <textarea>s. While these are often coloured, in an attempt at creating some sort of consistent colour scheme, it is rare that the site owner has made an effort to resize them. This creates an undesirable box only a few lines high rendering the inner code impossible to read.

It would be easy to address this problem with a few lines of CSS, but why bother when the method is inherently flawed? <textarea>s are a form of input. That means they were designed for users to enter text in, not the webmasters. There is no reason to continue this abuse of the <textarea> when a semantically correct and certainly obvious ‘replacement’ exists: <code>

The correct way of displaying code is with the <code>, or <pre> tags. <code> is an excellent way of marking up small snippets, like the code/pre tags in this paragraph. <pre> is ideal for larger blocks of code, as it retains any tabs and line breaks without having to add superfluous &nbsp;s, etc. Both can be styled equally easily with CSS.

  1. First, convert the code into its entity equivalents. This stops the code from actually turning into elements on the page.
  2. Next, decide which is better for your code block, <code> or <pre> using the above paragraph.
  3. Surround your converted code with the <code> or <pre> tags.
  4. Style with CSS using your custom properties, or an example set out below.

Code Snippets & Examples

Feel free to use any of these snippets to style your own <code>/<pre> tags :)

Code (for inline code samples)

Example: code example 1

Code: code { font: 11px/1 Courier New, monospace; color: #f00; }

Example: code example 2
Code: code { background: #ffc; font: 12px/1 Courier New, monospace; color: #090; }

Example: code example 3

Code: code { background: url(your image here); font: 13px/1 Georgia, serif; color: #000; }

Pre (for block-level code samples)

Note: overflow: auto; enables the scrollbars and must be included, otherwise the inner code will not adhere to the width/height properties.

Example: pre example 1
Code: pre { width: 400px; height: 50px; overflow: auto; border: 1px solid #fcc; padding: 5px; font: 11px/1 Courier New, monospace; color: #f00; }

Example: pre example 2
Code: pre { background: url(your image here); width: 400px; height: 100px; overflow: auto; border: 1px solid #f00; padding: 5px; font: 12px/1.2 Courier New, monospace; color: #000; }

You are limited only by your own creativity…

See also – How To Display Code Examples On Your Website