Do you know the best way to display code on your website?

Last updated by Brady Stroud [SSW] almost 2 years ago.See history

Any website designer that needs to display code should be aware that there is a very simple method for simply formatting code, and there is a slow and complex method.

The complex method requires formatting each line with HTML tags (such as <br> and  ) to ensure the code looks nice and pretty.

The simpler method uses <pre> tags. Pre (standing for "preformatted") means that the code is formatted exactly as it is written in the HTML window. This means the page designer can format code in a very simple fashion, without worrying about tags.

Note:  <code> tags should not be used because they only provide the font Courier - you still have to manually indent all of your code as in the bad code display example below.

<font face="Courier, Times, Arial, Verdana" size="3">
  public class Configuration
  {
    public static string MySetting { get; }
  }
</font>

Figure: Bad code display example - using <font>

<code>
  public class Configuration
  {
    public static string MySetting { get; }
  }

</code>

Figure: Bad code display example - using <code>

<pre>
  public class Configuration
  {
    public static string MySetting { get; }
  }
</pre>

Figure: Good code display example - using <pre>

Tip:  Do not use auto-format (Ctrl-K, Ctrl-F) in Visual Studio when updating page with <pre> tags, or it will destroy all the code formatting. We have made a suggestion to Microsoft to fix this.

We open source. Powered by GitHub