header-menu

Thursday, May 23, 2013

How to Show Programming Code on your Website or Blog

When we are writing tutorials or an example of code for any reason on our website or blog, it usually makes sense to make display that code as:


  1. Different block than the rest of the text.
  2. Attractive and easily readable
  3. With line numbers

Basically something like this:

  1. <div id='something'>
  2. <p>This is an example code</p>
  3. <a href='#'>example.com</p>
  4. </div>
Of course, the colors, fonts, background color of the block are all choice. But this is the basic structure we are looking to make.

Lets see how it is done with the following steps:

1 - First step is to write the code. If you writing on your blog or any CMS, just write the code in the 'view' or 'compose' mode. This, basically, is the other than the HTML mode. However, in case you are working on an IDE or text-editor, then you have type the code using special characters.

So '<' becomes '&lt;' and '>' becomes '&gt;'

2- When you are done with writing the code, wrap it in blockquote and make turn it into a list. You can do this either by clicking on 'quote' button while in the view/compose mode or by making the html look like this, in the HTML mode or your IDE

  1. <blockquote class="tr_bq">
  2. <ol style="text-align: left;">
  3. <li>&lt;div id='something'&gt;</li>
  4. <li>&lt;p&gt;This is an example code&lt;/p&gt;</li>
  5. <li>&lt;a href='#'&gt;example.com&lt;/p&gt;</li>
  6. <li>&lt;/div&gt;</li>
  7. </ol>
  8. </blockquote>

3- Now that you are done with the writing part, use the following CSS to give your display some style.

  1. <style>      
  2.       blockquote ol
  3.       {
  4.         background-color:#d8d8d8;
  5.         padding:10px 10px 10px 35px;
  6.         color:#FFF;
  7.       }
  8.       blockquote ol li:nth-child(even)
  9.       {
  10.         background-color:#b5d4e3;
  11.         color:#000;
  12.       }
  13.       blockquote ol li:nth-child(odd)
  14.       {
  15.         background-color:#b5def1;
  16.         color:#000;
  17.       }   
  18.     </style>
4- You can place this css code at the start of your page, in HTML mode. or if you are working with a CMS or a blog, then you can place it somewhere, from where it can apply to all your posts. For example: in blogger, you can go in template>edit HTML and place it between the <head> and </head>

In wordpress you can open Appearance>editor>style.css and place it at the end of the file. In this case though, remove the <style> and </style> from the above given code.

5- Now, save your file/post and try it out.


No comments:

Post a Comment