Home
Do you know the best way to display code on your website?
  v1.0 Posted at 6/08/2016 5:02 AM by Tiago Araujo

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 &nbsp;) 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<br>
&nbsp;{<br>
&nbsp;&nbsp;public static string MySetting<br>
&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;get<br>
&nbsp;&nbsp;&nbsp;{<br>
</font>

Figure: Bad code display example - using <font>

<code>
public class Configuration<br>
&nbsp;{<br>
&nbsp;&nbsp;public static string MySetting<br>
&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;get<br>
&nbsp;&nbsp;&nbsp;{<br>
</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.

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments:

    Note: Social Media login for Yotpo is not working in IE or Safari, please use Chrome. We are waiting for Yotpo to fix it.