Rules

Secret ingredients to quality software

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

Last updated by Tiago Araujo on 05 Aug 2016 07:02 pm (almost 5 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

&nbsp;{

&nbsp;&nbsp;public static string MySetting

&nbsp;&nbsp;{

&nbsp;&nbsp;&nbsp;get

&nbsp;&nbsp;&nbsp;{

</font>

Figure: Bad code display example - using <font>

<code>
public class Configuration

&nbsp;{

&nbsp;&nbsp;public static string MySetting

&nbsp;&nbsp;{

&nbsp;&nbsp;&nbsp;get

&nbsp;&nbsp;&nbsp;{

</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.

Adam CoganAdam Cogan

We open source. This page is on GitHub